How to parse and generate DateTime objects in ISO 8601 format
Solution 1:
The format you're describing is ISO 8601.
Since you're working with timestamps that inclulde a time zone component, I'd strongly recommend using DateTimeOffset
instead of DateTime
. It makes things so much easier!
To create a DateTimeOffset
for a given date, time, and time zone offset, use this syntax:
var date = new DateTimeOffset(2016, 3, 29, 12, 20, 35, 93, TimeSpan.FromHours(-5));
// March 29, 2016 at 12:20:35.93 GMT-5
This code will format a DateTimeOffset
as ISO 8601:
public static string FormatIso8601(DateTimeOffset dto)
{
string format = dto.Offset == TimeSpan.Zero
? "yyyy-MM-ddTHH:mm:ss.fffZ"
: "yyyy-MM-ddTHH:mm:ss.fffzzz";
return dto.ToString(format, CultureInfo.InvariantCulture);
}
And, to parse a string back to a DateTimeOffset
:
public static DateTimeOffset ParseIso8601(string iso8601String)
{
return DateTimeOffset.ParseExact(
iso8601String,
new string[] { "yyyy-MM-dd'T'HH:mm:ss.FFFK" },
CultureInfo.InvariantCulture,
DateTimeStyles.None);
}
If you must get back to a DateTime
you can get this from the DateTimeOffset
.UtcDateTime
property.
Solution 2:
A simpler way is to use the ToString method on DateTimeOffset with the "o" argument. This automatically prints the date in ISO8601 format
DateTimeOffset.Now.ToString("o");
The static parse method is also capable of correctly parsing a date in ISO8601 format.
DateTimeOffset.Parse("2016-25-12T20:45:30.3124+01:00");
DateTimeOffset.Parse("2016-25-12T20:45:30.3124Z");