DateTime.ParseExact format string

后端 未结 3 1738
清酒与你
清酒与你 2020-12-21 13:32

I have a web application that passes a DateTime from one page to another through the query string. It was working just fine in both IE and FireFox, but was throwing excepti

相关标签:
3条回答
  • 2020-12-21 13:45

    It may just be that your format doesn't cover the (Eastern Daylight Time) section. Try parsing that out of your string using regular string handling methods, then calling ParseExact on the remainder.

    Edit: As Oded points out, you'll also have to put the GMT into your format string as a literal:

    "ffffd MMM dd yyyy HH:mm:ss 'GMT'zzz"
    

    The following works:

    var input = "Wed Oct 03 2012 08:00:00 GMT-0400 (Eastern Daylight Time)";
    var trim = input.Substring(0, input.IndexOf(" ("));
    var dt = DateTime.ParseExact(
        trim,
        "ffffd MMM dd yyyy HH:mm:ss 'GMT'zzz",
        CultureInfo.InvariantCulture);
    
    0 讨论(0)
  • 2020-12-21 14:02

    I tried running the code

    static void Main(string[] args) {
        Console.WriteLine(DateTime.Now.ToString("ffffd MMM dd yyyy HH:mm:ss zzz"));            
        Console.Read();
    }
    

    Output is :

    Mon Oct 01 2012 10:52:20 -04:00

    So I guess you need to parse the GMT and (Eastern Daylight Time) part of strings as well

    0 讨论(0)
  • 2020-12-21 14:11

    Might I suggest that instead of passing something like: "Wed Oct 03 2012 08:00:00 GMT-0400 (Eastern Daylight Time)" in your query string, that instead you simply pass the timestamp of the date? E.g., new Date().getTime(). (Number of milliseconds since 1970 in UTC). Then, in C# you could just do:

    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    var dt =  epoch.AddMilliseconds(Convert.ToInt64(Request.QueryString["start"]));
    

    No parsing required.

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