I have a UTC DateTime value coming from a database record. I also have a user-specified time zone (an instance of TimeZoneInfo). How do I convert that UTC DateTime to the user's local time zone? Also, how do I determine if the user-specified time zone is currently observing DST? I'm using .NET 3.5.
Thanks, Mark
To do this, we will use the FindSystemTimeZoneById() of TimeZoneInfo class. This function takes Id as a parameter to return the equivalent time in timezone passed. In the example below, we are taking the current system time and converting it into “Central Standard Time”. DateTime currentTime = TimeZoneInfo.
Use the Date() constructor to convert UTC to local time, e.g. new Date(utcDateStr) . Passing a date and time string in ISO 8601 format to the Date() constructor converts the UTC date and time to local time.
SELECT CONVERT(datetime, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, GETUTCDATE()), DATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) AS LOCAL_IST; Here, the GETUTCDATE() function can be used to get the current date and time UTC. Using this query the UTC gets converted to local IST.
If you only need to convert from UTC to CST. You can simply use DATEADD(hour, -6, Timestamp) in your query.
The best way to do this is simply to use TimeZoneInfo.ConvertTimeFromUtc
.
// you said you had these already DateTime utc = new DateTime(2014, 6, 4, 12, 34, 0); TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); // it's a simple one-liner DateTime pacific = TimeZoneInfo.ConvertTimeFromUtc(utc, tzi);
The only catch is that the incoming DateTime
value may not have the DateTimeKind.Local
kind. It must either be Utc
, or Unspecified
.
You can use a dedicated function within TimeZoneInfo if you want to convert a DateTimeOffset into another DateTimeOffset:
DateTimeOffset newTime = TimeZoneInfo.ConvertTime( DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time") );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With