Kimberly
Kimberly

Reputation: 2697

How do I parse date strings with time zones like 'G8T' and 'G12T'?

In an ASP.NET application, I need to check the modified date when retrieving some images from a remote server. The header values for "Last-Modified" are strings like the following:

.NET's DateTime.Parse() method fails on these with a FormatException ("The string was not recognized as a valid DateTime. There is an unknown word starting at index 26."). Are there options I can pass to make a(ny) parsing method recognize those time zone indicators? I have not seen them before, and a Google search turns up some apparent usages on forums and similar sites, but no helpful information about what they mean.

(Oddly, the header values for "Date" on the same images end with "GMT". The remote server is IIS 7.5.)

Upvotes: 1

Views: 196

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500514

I can't easily check right now, but this might work:

DateTimeOffset result = DateTimeOffset.ParseExact(text,
    "ddd, dd MMM yyyy HH:mm:ss 'G'z'T'",
    CultureInfo.InvariantCulture);

That's using the z custom specifier... which would always format with a sign, but may not require one when parsing.

If you're happy to use bleeding-edge code, I believe Noda Time 1.2 (unreleased) should be able to cope with that using an OffsetDateTimePattern of ddd, dd MMM yyyy HH:mm:ss 'G'o<-H>'T'. Again, I can't test that right now but I'd expect it to work. It does mean running with currently-unreleased code though...

Upvotes: 2

Related Questions