Converting datetime to a particular time zone

To obtain the current time zone, you have two options: you can either acquire it using the first solution, or get the current offset with the second solution. It is important to save this information in the database along with the date and time. Nevertheless, it is worth noting that neither of these methods can accurately track time zone transitions, such as the switch between PST and PDT during daylight saving time in Pacific Time.


Solution:

Essentially, the method required for converting time to UTC would be TimeZoneInfo.ConvertTimeToUtc.

Ensure that the passed

DateTime

has its

Kind

property set to

Unspecified

. Otherwise, the method assumes specific requirements for the

sourceTimeZone

argument and throws an exception.

e.g.

var testTime = new DateTime(testDate.Year, testDate.Month, testDate.Day, 4, 0, 0);
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("West Asia Standard Time");
var utcTime = TimeZoneInfo.ConvertTimeToUtc(testTime, timeZoneInfo);;

Frequently Asked Questions

Posted in Uncategorized