How to convert string with unusual format into datetime

前端 未结 9 868
半阙折子戏
半阙折子戏 2021-01-19 17:15

I\'m using .NET 3.5 and I have a date that comes in as string in the following format:

Tue Jan 20 20:47:43 GMT 2009

First questi

相关标签:
9条回答
  • 2021-01-19 17:33
    DateTime.Parse("Tue Jan 20 20:47:43 GMT 2009")
    
    0 讨论(0)
  • 2021-01-19 17:41

    You could use Convert.ToDateTime

    0 讨论(0)
  • 2021-01-19 17:44

    Try to do a DateTime.Parse("Tue Jan 20 20:47:43 GMT 2009") and see if it accepts it.

    Here's a good link for custom DateTime formatting.

    http://msdn.microsoft.com/en-us/library/8kb3ffffd4.aspx

    I hope that helps.

    0 讨论(0)
  • 2021-01-19 17:44

    Try this:

    DateTime.TryParse(Tue Jan 20 20:47:43 GMT 2009", out objDt);
    

    You need to give an output value. Use If and if it returns true then its a valid date.

    HTH

    0 讨论(0)
  • 2021-01-19 17:45

    There you go

    DateTime d = DateTime.ParseExact("Tue Jan 20 20:47:43 GMT 2009".Replace("GMT", "+00"), "ffffd MMM dd H:mm:ss zz yyyy", new CultureInfo("en-US"));
    

    The DateTime API and its documentation pretty much sucks. Exceptions will only tell you that "String was not recognized as a valid DateTime", which doesn't really help. It had to figure out the date format specifiers myself because I didn't find them in MSDN.

    The "en-US" locale is necessary, I guess, because your date format uses English abbreviations like "Tue".

    Anyway, I can't tell you what the date format is called. It is pretty similar but not equal to a format used with HTTP (e.g. If-Modified-Since: Wed, 08 Dec 2004 13:25:25 GMT).

    0 讨论(0)
  • 2021-01-19 17:50
    DateTime dt;
    if(DateTime.TryParse("Tue Jan 20 20:47:43 GMT 2009", out dt)){
       /* Yay.. it's valid */
    }
    

    You can also use TryParseExact where you can specify the format of your DateTime

    Using TryparseExact

    const string FORMAT = "ffffd MMM dd HH:mm:ss \"GMT\" yyyy";
    if (DateTime.TryParseExact("Tue Jan 20 20:47:43 GMT 2009", FORMAT, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal, out dt)) {
            /* is valid */
     }    
    

    I believe that should work. Not sure if it will try to parse out the GMT though.

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