valid date check with DateTime.TryParse method

前端 未结 3 1939
旧时难觅i
旧时难觅i 2021-01-02 04:29

I am using Datetime.TryParse method to check the valid datetime. the input date string would be any string data. but is returning false as the specify date in i

相关标签:
3条回答
  • 2021-01-02 04:41

    You should be using TryParseExact as you seem to have the format fixed in your case.

    Something like can also work for you

    DateTime.ParseExact([yourdatehere],
                        new[] { "dd/MM/yyyy", "dd/M/yyyy" },
                        CultureInfo.InvariantCulture,
                        DateTimeStyles.None);
    
    0 讨论(0)
  • 2021-01-02 04:48

    You could use the TryParseExact method which allows you to pass a collection of possible formats that you want to support. The TryParse method is culture dependent so be very careful if you decide to use it.

    So for example:

    DateTime fromDateValue;
    string s = "15/07/2012";
    var formats = new[] { "dd/MM/yyyy", "yyyy-MM-dd" };
    if (DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
    {
        // do for valid date
    }
    else
    {
        // do for invalid date
    }
    
    0 讨论(0)
  • 2021-01-02 04:49

    As the others said, you can use TryParseExact.

    For more informations and the use with the time, you can check the MSDN Documentation

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