How to convert string with unusual format into datetime

前端 未结 9 980
半阙折子戏
半阙折子戏 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: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.

提交回复
热议问题