views:

832

answers:

5

Why can't it parse this:

DateTime.Parse("Tue, 1 Jan 2008 00:00:00 UTC")
A: 

Not sure why, but you can wrap DateTime.ToUniversalTime in a try / catch and achieve the same result in more code.

Good luck.

Ian P
+5  A: 

It can't parse that string because "UTC" is not a valid time zone designator.

UTC time is denoted by adding a 'Z' to the end of the time string, so your parsing code should look like this:

DateTime.Parse("Tue, 1 Jan 2008 00:00:00 Z");

From the Wikipedia article on ISO 8601

If the time is in UTC, add a 'Z' directly after the time without a space. 'Z' is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z".

UTC time is also known as 'Zulu' time, since 'Zulu' is the NATO phonetic alphabet word for 'Z'.

Simon P Stevens
The date string in my example came from internet explorer
Dve
@Dave: When you say it came from IE, do you mean that you extracted it from a web page? You may have to write your own replacement for the DateTime parser that extracts the UTC and replaces it with a Z.
Simon P Stevens
Having being testing against FF, I had forgotten I called the toUTCString() method on the date I POST back to the server. FF sends GMT while IE sends UTC. So I cant blame IE... this time!
Dve
+2  A: 

You need to specify the format:

DateTime date = DateTime.ParseExact(
    "Tue, 1 Jan 2008 00:00:00 UTC", 
    "ddd, d MMM yyyy HH:mm:ss UTC", 
    CultureInfo.InvariantCulture);
Darin Dimitrov
Nice suggestion, but this would fail if the provided date string didn't contain UTC at the end. Say instead you passed a date string that had +01 at the end, it would cause a FormatException. Depends what he is trying to do I suppose.
Simon P Stevens
A: 

or use the AdjustToUniversal DateTimeStyle in a call to

DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles)
Ive tried that, and it didnt seem to work
Dve
+2  A: 

It's not a valid format, however "Tue, 1 Jan 2008 00:00:00 GMT" is.

The documentation says like this:

A string that includes time zone information and conforms to ISO 8601. For example, the first of the following two strings designates the Coordinated Universal Time (UTC); the second designates the time in a time zone seven hours earlier than UTC:

2008-11-01T19:35:00.0000000Z

A string that includes the GMT designator and conforms to the RFC 1123 time format. For example:

Sat, 01 Nov 2008 19:35:00 GMT

A string that includes the date and time along with time zone offset information. For example:

03/01/2009 05:42:00 -5:00

HackerBaloo