Convert a string to a date in .net

后端 未结 6 1550
忘了有多久
忘了有多久 2020-12-10 15:21

I\'m reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest

相关标签:
6条回答
  • 2020-12-10 15:48

    you could try also TryParseExact for set exact format. method, here's documentation: http://msdn.microsoft.com/en-us/library/ms131044.aspx

    e.g.

    DateTime outDt;
    bool blnYYYMMDD = 
         DateTime.TryParseExact(yourString,"yyyyMMdd"
                                ,CultureInfo.CurrentCulture,DateTimeStyles.None
                                , out outDt);
    

    I hope i help you.

    0 讨论(0)
  • 2020-12-10 15:54

    DateTime.TryParse method

    0 讨论(0)
  • 2020-12-10 15:55

    Using TryParse will not throw an exception if it fails. Also, TryParse will return True/False, indicating the success of the conversion.

    Regards...

    0 讨论(0)
  • 2020-12-10 16:01

    You can also do Convert.ToDateTime

    not sure the advantages of either

    0 讨论(0)
  • 2020-12-10 16:06
    string[] formats = {"yyyyMMdd", "MM/dd/yy"};
    var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
    

    or

    DateTime result;
    string[] formats = {"yyyyMMdd", "MM/dd/yy"};
    DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);
    

    More info in the MSDN documentation on ParseExact and TryParseExact.

    0 讨论(0)
  • 2020-12-10 16:07

    You can use the TryParse method to check validity and parse at same time.

    DateTime output;
    string input = "09/23/2008";
    if (DateTime.TryParseExact(input,"MM/dd/yy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output) || DateTime.TryParseExact(input,"yyyyMMdd", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output))
    {
        //handle valid date
    }
    else
    {
        //handle invalid date
    }
    
    0 讨论(0)
提交回复
热议问题