Alexandru Marculescu Alexandru Marculescu - 11 months ago 62
C# Question

Trouble parsing (almost) RoundtripKind date in C#

I'm consuming a Java client which returns me a Date like

2016-09-02T16:18:54.000 UTC
. Notice the ending, which is not exactly standard format.

If I trim the "UTC" I can successfully parse the date:


but the result's Kind is Unspecified, instead of UTC (obviously); I can bypass that by replacing "UTC" with "Z" like so:

DateTime.Parse("2016-09-02T16:18:54.000Z", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind)

However ideally I'd like not to mess with the input.

Took a couple of stabs at this with TryParseExact and different formats but failed with each one:

DateTime.TryParseExact("2016-09-02T16:18:54.000 UTC", new [] {
"yyyy-MM-dd hh:mm:ss:fff UTC",
"yyyy-MM-ddhh:mm:ss:fff UTC",
"yyyy-MM-ddThh:mm:ss:fff UTC"
}, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out startDate)

I'm pretty sure the "UTC" keyword is not the issue (since others have successfully used it), but rather that "T" that I can't seem to know how to parse: not even the "o" format that I think was implicitly used in my second code snippet seems to work:

DateTime.TryParseExact("2016-09-02T16:18:54.000Z", "o", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out startDate)

Answer Source

If your input is like 2016-09-02T16:18:54.000 UTC,this works for me:

DateTime.TryParseExact("2016-09-02T16:18:54.000 UTC", 
"yyyy-MM-ddTHH:mm:ss.fff UTC"
, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out startDate);