Tony
Tony

Reputation: 12695

C# parse GMT date string to DateTime

I'm using http://www.eyecon.ro/bootstrap-datepicker/ plugin to select date, and after date is selected I get e.g. Fri Nov 01 2013 00:00:00 GMT+0100

1) Why am I getting that date format if I set up the plugin with format yyyy-mm-dd ?

2) How to parse Fri Nov 01 2013 00:00:00 GMT+0100 to DataTime with format yyyy-mm-dd ?

Upvotes: 5

Views: 10595

Answers (2)

Abdullah Tahan
Abdullah Tahan

Reputation: 2129

    public string GmtDateTimeString { get; set; }
     
    public static readonly string[] DateFormats =
    {
                "MM/dd/yyyy hh:mm:ss tt",
                "MM/dd/yyyy HH:mm:ss"
    };

    public bool TryParseUtcDate(out DateTime d)
    {
                if (DateTime.TryParseExact(GmtDateTimeString, DateFormats,
                    CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out d))
                {
                    return true;
                }
    
                if (DateTime.TryParse(GmtDateTimeString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out d))
                {
                    return true;
                }
    
                d = DateTime.MinValue;
    
                return false;
   }

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98750

You can use "ddd MMM dd yyyy HH:mm:ss 'GMT'K" format with DateTime.ParseExact like;

string s = "Fri Nov 01 2013 00:00:00 GMT+0100";
DateTime dt = DateTime.ParseExact(s, "ddd MMM dd yyyy HH:mm:ss 'GMT'K",
                       CultureInfo.InvariantCulture);
Console.WriteLine(dt);

Output will be;

10/31/2013 11:00:00 PM

Here a demonstration.

For more informations, take a look at;

Upvotes: 11

Related Questions