C# 使用 DateTime.TryParse 检查字符串是否为有效日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16075159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:55:42  来源:igfitidea点击:

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

c#.net

提问by Kai

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 returns truefor even strings like "1-1", "1/1" .etc.

我正在使用DateTime.TryParse()函数来检查特定字符串是否是不依赖于任何文化的有效日期时间。
令我惊讶的是,该函数返回true偶数字符串,如“1-1”、“1/1”等。

How can I solve this problem?

我怎么解决这个问题?

Update:

更新:

Does it mean, if I want to check if a particular string is valid datetime, I need a huge array of formats?? There will be different combinations , I believe.
Even there are lots of date separator ( '.' , '/' , '-', etc..) depending on the culture, it will be difficult for me to define an array of format to check against .
Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution?
So, if the value includes any parts of time, it should return true too. I could NOT be able to define a array of format.

这是否意味着,如果我想检查特定字符串是否为有效日期时间,我需要大量格式?我相信会有不同的组合。
即使有很多日期分隔符( '.' 、 '/' 、 '-' 等)取决于文化,我也很难定义一组格式来检查 .
基本上,我想检查一个特定的字符串是否以任何顺序包含至少天(1 到 31 或 01 到 31)、月(1 到 12 或 01 到 12)和年(yyyy 或 yy),带有任何日期分隔符,解决办法是什么?
因此,如果该值包含时间的任何部分,它也应该返回 true。我无法定义格式数组。

采纳答案by Habib

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

如果您希望您的日期符合特定格式或格式,则DateTime.TryParseExact否则使用这是默认行为DateTime.TryParse

DateTime.TryParse

日期时间.TryParse

This method tries to ignore unrecognized data, if possible, and fills in missing month, day, and yearinformation 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.

如果可能,此方法会尝试忽略无法识别的数据,并使用当前日期填充缺失的月、日和年信息。如果 s 仅包含日期而没有时间,则此方法假定时间为午夜 12:00。如果 s 包含具有两位数年份的日期组件,则它会根据 Calendar.TwoDigitYearMax 属性的值转换为当前区域性的当前日历中的年份。s 中的任何前导、内部或尾随空白字符都将被忽略。

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:

如果您想针对多种格式进行确认,请查看DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime)重载。来自同一链接的示例:

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.

回答by Mudassir Hasan

Use DateTime.TryParseExact()if you want to match against a specific date format

使用 DateTime.TryParseExact(),如果你要匹配特定的日期格式

 string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
    DateTimeStyles.None, out dateTime))
{
    Console.WriteLine(dateTime);
}
else
{
    Console.WriteLine("Not a date");
}

回答by User 12345678

[TestCase("11/08/1995", Result= true)]
[TestCase("1-1", Result = false)]
[TestCase("1/1", Result = false)]
public bool IsValidDateTimeTest(string dateTime)
{
    string[] formats = { "MM/dd/yyyy" };
    DateTime parsedDateTime;
    return DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"),
                                   DateTimeStyles.None, out parsedDateTime);
}

Simply specify the date time formats that you wish to accept in the array named formats.

只需在名为format的数组中指定您希望接受的日期时间格式

回答by SBirthare

Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution? So, if the value includes any parts of time, it should return true too. I could NOT be able to define a array of format.

基本上,我想检查一个特定的字符串是否以任何顺序包含至少一天(1 到 31 或 01 到 31)、月(1 到 12 或 01 到 12)和年(yyyy 或 yy),带有任何日期分隔符,解决办法是什么?因此,如果该值包含时间的任何部分,它也应该返回 true。我无法定义格式数组。

When I was in a similar situation, here is what I did:

当我处于类似情况时,我是这样做的:

  1. Gather all the formats my system is expected to support.
  2. Looked at what is common or can be generalize.
  3. Learned to create REGEX (It is an investment of time initially but pays off once you create one or two on your own). Also do not try to build REGEX for all formats in one go, follow incremental process.
  4. I created REGEX to cover as many format as possible.
  5. For few cases, not to make REGEX extra complex, I covered it through DateTime.Parse() method.
  6. With the combination of both Parse as well as REGEX i was able to validate the input is correct/as expected.
  1. 收集我的系统预期支持的所有格式。
  2. 看看什么是共同的或可以概括的。
  3. 学会了创建 REGEX(最初需要投入时间,但一旦您自己创建一两个就会得到回报)。也不要尝试一次性为所有格式构建 REGEX,遵循增量过程。
  4. 我创建了 REGEX 以涵盖尽可能多的格式。
  5. 对于少数情况,为了不让 REGEX 变得更加复杂,我通过 DateTime.Parse() 方法对其进行了介绍。
  6. 通过 Parse 和 REGEX 的组合,我能够验证输入是否正确/如预期。

This http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simplewas really helpful both for understanding as well as validation the syntax for each format.

这个http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simple对于理解和验证每种格式的语法非常有帮助。

My 2 cents if it helps....

如果有帮助,我的 2 美分...

回答by Anil Mohapatra

Try using

尝试使用

DateTime.ParseExact(
    txtPaymentSummaryBeginDate.Text.Trim(),
    "MM/dd/yyyy", 
    System.Globalization.CultureInfo.InvariantCulture
);

It throws an exception if the input string is not in proper format, so in the catchsection you can return false;

如果输入字符串的格式不正确,它会抛出异常,因此在该catch部分中,您可以return false;

回答by Deathstalker

So this question has been answered but to me the code used is not simple enough or complete. To me this bit here is what I was looking for and possibly some other people will like this as well.

所以这个问题已经得到回答,但对我来说使用的代码不够简单或完整。对我来说,这就是我一直在寻找的东西,可能其他一些人也会喜欢这个。

string dateString = "198101";

if (DateTime.TryParse(dateString, out DateTime Temp) == true)
{
     //do stuff
}

The output is stored in Tempand not needed afterwards, datestringis the input string to be tested.

输出存储在Temp并且以后不需要,datestring是要测试的输入字符串。