I'm implementing conditional requests in a Web service. The backend can easily retrieve the last modified date of an entity, so I'm sending Last-Modified and getting back If-Modified-Since. The RFC for HTTP Dates specifies a format that is the same as the "R" format specifier in .NET.
The problem is that DateTime.ToString("R")
formats the date correctly, but passing "R"
to ParseExact
doesn't read the time zone back (there is a "Round trip" specifier, "O"
, but it's not in the format I need). Here's an example in LinqPad:
DateTime lastModified = new DateTime(2015, 10, 01, 00, 00, 00, DateTimeKind.Utc);
string lastModifiedField = lastModified.ToString("R"); // Thu, 01 Oct 2015 00:00:00 GMT
DateTime ifModifiedSince = DateTime.ParseExact(
lastModifiedField, "R", CultureInfo.InvariantCulture);
ifModifiedSince.Kind.Dump(); // Unspecified
I can certainly use methods on the parsed DateTime
to force it into the format I want, but how can I get the framework to use the data that's already there?
Kind
will always beUtc
, since you obtained it from.UtcDateTime
. But at least the parsing is correct. You'll be interested to also observe thatDateTime.Parse
does work - at least it does when you passDateTimeStyles.RoundtripKind
. It's onlyDateTime.ParseExact
that doesn't. – Drona