How to convert convert_tz() in mysql to a c# function
2 Answers
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

- 1
- 3
-
I know but I am trying to find something that can do what I was looking for. I am relatively new to c# libraries and there are so many different timezone functionalities that i'm a bit lost – Andy Jul 01 '21 at 21:17
-
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"));
}

- 97,193
- 102
- 206
- 364

- 58
- 7