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
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.
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.
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.
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)
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