Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Specify Source Time Zone When converting between two Time Zones

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading