52

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

我怎么解决这个问题?

更新:

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

4

7 回答 7

63

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

日期时间.TryParse

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

如果您想确认多种格式,请查看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.
于 2013-04-18T05:40:20.507 回答
18

如果 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");
}
于 2013-04-18T05:37:02.713 回答
15
[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);
}

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

于 2013-04-18T05:44:11.737 回答
2

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

string dateString = "198101";

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

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

于 2018-01-04T20:52:19.493 回答
1

另一种方法是创建一种方法来验证文本是否为 Date 类型。

public bool IsDateTime(string date)
{
    if (string.IsNullOrEmpty(date)) return false;
    return DateTime.TryParse(date, out DateTime dateTime);
}
于 2021-07-13T20:32:10.463 回答
0

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

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

  1. 收集我的系统预期支持的所有格式。
  2. 看看什么是常见的或可以概括的。
  3. 学会了创建正则表达式(最初是一种时间投资,但一旦你自己创建一两个就会得到回报)。也不要尝试一次性为所有格式构建 REGEX,遵循增量过程。
  4. 我创建了 REGEX 以涵盖尽可能多的格式。
  5. 在少数情况下,为了不使 REGEX 更加复杂,我通过 DateTime.Parse() 方法对其进行了介绍。
  6. 通过 Parse 和 REGEX 的结合,我能够验证输入是否正确/符合预期。

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

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

于 2013-04-18T08:53:07.283 回答
0

尝试使用

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

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

于 2015-08-04T15:11:18.503 回答