Parse Javascript date to C# DateTime

后端 未结 1 735
执笔经年
执笔经年 2021-01-21 00:31

I have date object in JavaScript which give me: \"Wed Oct 01 2014 00:00:00 GMT+0200\";

I try to parse it but I get an exception:

string Date         


        
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-21 00:48

    MM format specifier is 2 digit month number from 01 to 12.

    You need to use MMM format specifier instead for abbreviated name of month.

    And for your +0200 part, you need to use K format specifier which has time zone information instead of zzzzz.

    And you need to use single quotes for your GMT part as 'GMT' to specify it as literal string delimiter.

    string s = "Wed Oct 01 2014 00:00:00 GMT+0200";
    DateTime dt;
    if(DateTime.TryParseExact(s, "ffffd MMM dd yyyy HH:mm:ss 'GMT'K", 
                              CultureInfo.InvariantCulture,
                              DateTimeStyles.None, out dt))
    {
        Console.WriteLine(dt);
    }
    

    Any z format specifier is not recommended with DateTime parsing. Because they represents signed offset of local time zone UTC value and this specifier doesn't effect DateTime.Kind property. And DateTime doesn't keep any offset value.

    That's why this specifier fits with DateTimeOffset parsing instead.

    0 讨论(0)
提交回复
热议问题