Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...