Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert UTC DateTime to another Time Zone

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

like image 763
Mark Richman Avatar asked Mar 30 '10 19:03

Mark Richman


People also ask

How do I convert datetime to another time zone?

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.

How do I convert UTC date to Localdatetime?

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.

How do I convert UTC to local time zone in SQL?

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.

How do I convert UTC to Central time in SQL?

If you only need to convert from UTC to CST. You can simply use DATEADD(hour, -6, Timestamp) in your query.


2 Answers

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.

like image 66
Matt Johnson-Pint Avatar answered Sep 19 '22 15:09

Matt Johnson-Pint


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") ); 
like image 38
Erwin Mayer Avatar answered Sep 18 '22 15:09

Erwin Mayer