带时区的日期时间到字符串

我有一个以值 2010年01月01日01:01:01:01的通用时间(UTC)存储的 DateTime。

我想在 EST 中以这种格式 2010年01月01日04:01:01格林尼治标准时间04:00显示它,但是时区的‘ K’格式化程序在 ToString 中不起作用

130829 次浏览

I think you are looking for the TimeZoneInfo class (see http://msdn.microsoft.com/en-us/library/system.timezoneinfo_members.aspx). It has many static methods to convert dates between time zones.

Something like this works. You could probably clean it up a bit more:

string newDate = string.Format("{0:yyyy-MM-dd HH:mm:ss} GMT {1}", dt.ToLocalTime(), dt.ToLocalTime().ToString("%K"));

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.

This method will return the specified time in Eastern Standard Time (as the question requested), even if EST is not the local time zone:

public string GetTimeInEasternStandardTime(DateTime time)
{
TimeZoneInfo easternStandardTime = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTimeOffset timeInEST = TimeZoneInfo.ConvertTime(time, easternStandardTime);
return timeInEST.ToString("yyyy-MM-dd hh:mm:ss tt\" GMT\"zzz");
}

Note: I haven't tested this in a non-English OS. See the MSDN documentation on TimeZoneInfo.FindSystemTimeZoneById.

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)