Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime to string with time zone

Tags:

c#

datetime

I have a DateTime stored in universal time (UTC) of value 2010-01-01 01:01:01.

I would like to display it in EST in this format 2010-01-01 04:01:01GMT-04:00, however the 'K' formatter for timezone doesn't work in ToString

like image 589
Comma Avatar asked Jul 23 '10 23:07

Comma


People also ask

Does datetime include timezone?

A DateTime value defines a particular date and time. It includes a Kind property that provides limited information about the time zone to which that date and time belongs.

How do I convert a date to a different time zone?

To convert a date to another time zone: Use the toLocaleString() method to get a string that represents the date according to the provided time zone. Pass the result to the Date() constructor. The returned Date object will have its date and time set according to the provided time zone.


2 Answers

Use the "zzz" format specifier to get the UTC offset. For example:

        var dt = new DateTime(2010, 1, 1, 1, 1, 1, DateTimeKind.Utc);         string s = dt.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz");         Console.WriteLine(s); 

Output: 2009-12-31 19:01:01 GMT-06:00

I'm in the CDT timezone. Make sure the DateTime is unambiguously DateTimeKind.Utc.

like image 93
Hans Passant Avatar answered Sep 19 '22 08:09

Hans Passant


If like myself you happen to need a format like 2018-03-31T01:23:45.678-0300 (no colon in the timezone part), you can use this:

datetime.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz").Remove(26,1) 
like image 20
Andrew Avatar answered Sep 21 '22 08:09

Andrew