datetime to string with time zone

C#Datetime

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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)

Solution 3 - C#

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.

Solution 4 - C#

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"));

Solution 5 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCommaView Question on Stackoverflow
Solution 1 - C#Hans PassantView Answer on Stackoverflow
Solution 2 - C#AndrewView Answer on Stackoverflow
Solution 3 - C#Jon SchneiderView Answer on Stackoverflow
Solution 4 - C#RobaticusView Answer on Stackoverflow
Solution 5 - C#Philip SmithView Answer on Stackoverflow