Search code examples
c#.netdatetimetimezonedate-formatting

datetime to string with time zone


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


Solution

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