Check if a string is a valid date using DateTime.TryParse

前端 未结 6 1981
梦谈多话
梦谈多话 2020-11-30 05:27

I am using DateTime.TryParse() function to check if a particular string is a valid datetime not depending on any cultures.
To my surprise , the function re

6条回答
  •  借酒劲吻你
    2020-11-30 06:00

    If you want your dates to conform a particular format or formats then use DateTime.TryParseExact otherwise that is the default behaviour of DateTime.TryParse

    DateTime.TryParse

    This method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes the time is 12:00 midnight. If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space character in s is ignored.

    If you want to confirm against multiple formats then look at DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime) overload. Example from the same link:

    string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                       "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                       "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                       "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                       "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
    string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                            "5/1/2009 6:32:00", "05/01/2009 06:32", 
                            "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
    DateTime dateValue;
    
    foreach (string dateString in dateStrings)
    {
       if (DateTime.TryParseExact(dateString, formats, 
                                  new CultureInfo("en-US"), 
                                  DateTimeStyles.None, 
                                  out dateValue))
          Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
       else
          Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
    }
    // The example displays the following output: 
    //       Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM. 
    //       Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM. 
    //       Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM. 
    //       Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM. 
    //       Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM. 
    //       Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
    

提交回复
热议问题