I’m working with the following Time Zone code:
using System.Globalization;
DateTime sourceDt = Convert.ToDateTime("2023-09-05T08:00:00");
DateTime sourceUtc = sourceDt.ToUniversalTime();
var tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var tzTime = TimeZoneInfo.ConvertTimeFromUtc(sourceUtc, tz);
Console.WriteLine("Time1= " + tzTime.ToString("hh:mm tt",
CultureInfo.InvariantCulture));
var tz2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var tz2Time = TimeZoneInfo.ConvertTimeFromUtc(sourceUtc, tz2);
Console.WriteLine("Time2= " + tz2Time.ToString("hh:mm tt",CultureInfo.InvariantCulture));
Time1 outputs 07:00 AM and Time2 outputs 08:00 AM. I’m assuming this is because I’m in EST. Is there a way I can specify that what time zone sourceDt is in?
For example, I would like sourceDt to be in CST and have Time1 output 08:00 AM and Time2 output 09:00 AM.
>Solution :
Use the TimeZoneInfo.ConvertTimeToUtc method to convert a local time to utc time while specifying the source time zone.
var tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var tz2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime sourceDt = Convert.ToDateTime("2023-09-05T08:00:00");
DateTime sourceUtc = TimeZoneInfo.ConvertTimeToUtc(sourceDt, tz);
var tzTime = TimeZoneInfo.ConvertTimeFromUtc(sourceUtc, tz);
Console.WriteLine("Time1= " + tzTime.ToString("hh:mm tt", CultureInfo.InvariantCulture));
var tz2Time = TimeZoneInfo.ConvertTimeFromUtc(sourceUtc, tz2);
Console.WriteLine("Time2= " + tz2Time.ToString("hh:mm tt", CultureInfo.InvariantCulture));
Console.ReadLine();
Output:
Time1= 08:00 AM
Time2= 09:00 AM