Cheetah
Cheetah

Reputation: 14379

Converting a DateTime to Utc given a timezone

I don't want to keep having to change the config everytime there is a daylight savings change. This is what I am currently doing which doesn't work as it uses "Standard" time.

TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time")
TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZone); // This doesn't take into account that it's daylight savings...

Is there a one size fits all solution. So I can give it a datetime and a location like "US east coast" and it give me the time in Utc?

Upvotes: 0

Views: 4264

Answers (2)

Sushil
Sushil

Reputation: 1131

You Can Pass DateTime and TimeZone of the Location and Convert the provided DateTime to UTC

Check this Example Here

       string DisplayName = "custom standard name here";//custom Standard Name to display eg: Kathmandu
       string StandardName = "custom standard name here"; // custom Standard Name eg: Asia/Kathamandu, Nepal
       string YourDate="27-03-2019 20:24:56"; // this DateTime doesn't contain any timeZone
       TimeSpan Offset = new TimeSpan(+5, 30, 00);// your TimeZone offset eg: timeZone of Nepal is +5:45
       TimeZoneInfo TimeZone = TimeZoneInfo.CreateCustomTimeZone(StandardName, Offset, DisplayName, StandardName);
       var RawDateTime = DateTime.SpecifyKind(DateTime.Parse(YourDate), DateTimeKind.Unspecified);// I all it RawDateTime Since it doesn't contain any TimeSpan
       DateTime UTCDateTime = TimeZoneInfo.ConvertTimeToUtc(RawDateTime, TimeZone);
       Console.WriteLine(UTCDateTime);

Upvotes: 1

Freelancer
Freelancer

Reputation: 9064

I've done it before by storing the timezone id in the database using a mapping table. i.e. A table containing the results of TimeZone.GetSystemTimeZones()

You don't actually need to use TimeZoneInfo.FindSystemTimeZoneById() though: you can do the conversion using one of the overloads of TimeZoneInfo.ConvertTimeBySystemTimeZoneId(). This method has some overloads which take DateTime values, and some that take DateTimeOffset values (which are preferable as they specify an unambiguous point in time).

e.g.

TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "New Zealand Standard Time", "UTC")

The real benefit of using the system time zone id rather than an offset stored in the database is that daylight savings time is automatically handled for you by TimeZoneInfo.ConvertTimeBySystemTimeZoneId.

This msdn also might prove helpful to you>

http://msdn.microsoft.com/en-us/library/bb382058.aspx

Upvotes: 5

Related Questions