views:

154

answers:

2

Hello, I'm performing an HttpWebRequest against an IIS server. One of the response headers is Date, which I'd like to parse. This is its value:

"Sun, 11 Oct 2009 08:16:13 GMT"

How do I parase this string? DateTime.Parse didn't quite work out well for me.

Thanks!

A: 

use DateTime.TryParse

var d = "Sun, 11 Oct 2009 08:16:13 GMT";
DateTime dt;
var b = DateTime.TryParse(d, CultureInfo.InvariantCulture.DateTimeFormat, 
    DateTimeStyles.None, out dt);
Console.WriteLine(dt);

Outputs:

11-10-2009 01:46:13

Note: the time is little off the mark, I think it is being converted to local time.

TheVillageIdiot
+3  A: 

You can use DateTime.ParseExact to specify the exact format you are attempting to parse. Without testing, it looks like you'll need:

DateTime.ParseExact(input, "ddd, dd MMM yyyy HH:mm:ss K");

Or, if the GMT gives you trouble, use the DateTimeStyles overload of ParseExact:

DateTime.ParseExact(input, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", 
    CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal);
Richard Szalay