Since you are asking about best practices:
Do not use the
TimeZone
class. If you need time zone conversions, use theTimeZoneInfo
class instead. This is very clear in the MSDN documentation:Whenever possible, avoid any use of "local" time. It is local to the system where the code is running. In the vast majority of real-world use cases, it is likely that it is not the local time zone of your user. This is especially true in a web application.
That means you should not be calling any of the following:
DateTime.Now
TimeZone.CurrentTimeZone
TimeZoneInfo.Local
DateTime.ToLocalTime()
DateTime.ToUniversalTime()
- Any other method that involves the server's local time zone.
Instead, your application should allow the user to select a time zone, then you can convert to and from the local time in that zone using the
TimeZoneInfo.Convert...
methods.If you need the current universal time, use
DateTime.UtcNow
orDateTimeOffset.UtcNow
.If you need the current local time zone of your server, ONLY use
DateTimeOffset.Now
.If you need the current local time in a known time zone, such as US Eastern Time:
DateTime easternNow = TimeZoneInfo.ConvertTimeBySystemTimeZoneId( DateTime.UtcNow, "Eastern Standard Time");
If you want to convert between a known time zone and UTC, then use the
TimeZoneInfo.ConvertTimeToUtc
andTimeZoneInfo.ConvertTimeFromUtc
methods, and be sure to pass in the time zone you are converting to/from:// get the local time zone of your user, not of the server! TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); // use this to convert from UTC to local DateTime local = TimeZoneInfo.ConvertTimeFromUtc(yourUtcDateTime, tzi); // use this to convert from local to UTC DateTime utc = TimeZoneInfo.ConvertTimeToUtc(yourLocalDateTime, tzi);
Be aware that when you convert from local to UTC, you might encounter ambiguities during daylight saving time transitions. Read more in the DST tag wiki.
Additional reading: The Case Against DateTime.Now