Timezone conversion mysql funtion to c#

188 Views Asked by At

How to convert convert_tz() in mysql to a c# function

2

There are 2 best solutions below

2
On

edit:

Use TimeZoneInfo and choose zone by it's id (here's why and how to check them)

IMPORTANT - This data is not static. New time zones are introduced into Windows as the governments of the world make changes. This is ultimately why there are not authoritative pages listing them in the docs. Do not rely on any hardcoded list, but call TimeZoneInfo.FindTimeZoneById() yourself, or use TZUTIL.EXE /L to list them. The answers below are only but a snapshot of the data at the time they were reported. DO NOT COPY FROM HERE TO HARDCODE INTO YOUR APPLICATION!

Example of code:

var exampleTime = DateTime.SpecifyKind(DateTime.Now,DateTimeKind.Unspecified);

DateTime result = TimeZoneInfo.ConvertTime(exampleTime,
TimeZoneInfo.FindSystemTimeZoneById("Europe/London"),
TimeZoneInfo.FindSystemTimeZoneById("America/Denver")); 

Before changes in question:

There's not such an overload for this method with such parameters.

TimeZoneInfo.ConvertTime overloads - documentation screen

Source: Microsoft Documentation

0
On

There are probably cleaner methods, but I keep a helper function that uses TimeZoneInfo(search the MS documentation to find the particular ID you need) in a custom TimeUtils class

public static DateTime ConvertToMST(DateTime dt)
{
    DateTime utc = dt.ToUniversalTime();
    return TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"));
}