8

I'm trying to parse the date from the Last-Modified header in an HTTP response.

The date shows as follow:

Last-Modified: Sat, 01 Jul 2006 01:50:55 UTC

I tried DateTime.Parse, DateTime.ParseExact with no success.

What is that UTC thing at the end and why does C# doesn't want to parse it?

Update:

  • The server I am requesting from is PWS/8.0.16 which (i think) is Windows Personal Web Server... This server might be the culprit. (I am interested to know what this server is)
  • The data consists of jpeg images.
  • It seems like the date format for the Last-Modified header is not always the same. Sometimes, it ends with UTC. Others with GMT.
KavenG
  • 161
  • 1
  • 9
  • 1
    Relevant http://stackoverflow.com/questions/1756639/why-cant-datetime-parse-parse-utc-date – keyboardP Oct 02 '13 at 20:45
  • KavenG - if the answer was helpful to you - upvote it please. If it was the solution - upvote + update ) – MikroDel Oct 02 '13 at 20:48
  • 1
    This header value seems incorrect. "UTC" is not expected here, only "GMT", http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 (it's an rfc1123-date). If it was correct you could use `DateTime.ParseExact(text, "r", null)` – Simon Mourier Oct 02 '13 at 21:23
  • The question linked by keyboardP answers the question but the scenario is different. Should we keep both since this one is more detailed and specific? – KavenG Oct 02 '13 at 22:47

1 Answers1

10

Use ParseExact to specify the input format:

string inputDate = "Sat, 01 Jul 2006 01:50:55 UTC";

DateTime time = DateTime.ParseExact(inputDate,
                    "ddd, dd MMM yyyy HH:mm:ss 'UTC'",
                    CultureInfo.InvariantCulture.DateTimeFormat,
                    DateTimeStyles.AssumeUniversal);
JLe
  • 2,835
  • 3
  • 17
  • 30
  • This solution is great if the date always ends with UTC. Use DateTimeStyles.AdjustToUniversal to keep the date as UTC. Otherwise, it will be converted to local. – KavenG Oct 02 '13 at 22:53
  • 1
    Also according https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified it should always end in 'GMT', not 'UTC'. – Bogdan Kiselitsa Oct 31 '19 at 08:46