DateTime.TryParseExact 不起作用 - 返回 false,但应该为 true



我尝试使用 TryParseExact 验证 DateTime 对象。任务是检查日期时间是否包含时间,而不仅仅是日期。到目前为止,我拥有的代码:

public bool validateDateAndTime(DateTime checkDateFormat)
{
checkDateFormat = new DateTime(2019, 02, 02, 23, 33, 21); 
DateTime checkOutDate; 
if(DateTime.TryParseExact(checkDateFormat.ToString(), "yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out checkOutDate))
{
return true;
}
else
{
Console.WriteLine(checkDateFormat.ToString() + " " + checkOutDate);
return false;
}
}

这对我来说毫无意义,因为我在 if 案例之前设置了"yyyy, mm, dd, hh, mm, ss"

打印的控制台行:

2019-02-02 23:

33:21 0001-01-01 00:00:00

您的 ToString(( 输出与 yyyy-MM-dd hh:mm:ss 的确切格式不匹配:

public bool validateDateAndTime(DateTime checkDateFormat)
{
checkDateFormat = new DateTime(2019, 02, 02, 23, 33, 21);
if (DateTime.TryParseExact(checkDateFormat.ToString("yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out DateTime checkOutDate))
{
Console.WriteLine($"Validated: {checkOutDate}");
return true;
}
else
{
Console.WriteLine(checkDateFormat.ToString() + " " + checkOutDate);
return false;
}
}

您实际上是在转换 DateTime.ToString((,默认情况下它是常规格式,并且属于 en-US 区域性。

如果要以其他格式显示时间,请指定其格式。

试试这个,

DateTime.TryParseExact(checkDateFormat.ToString("yyyy-MM-dd hh:mm:ss"), "yyyy-MM-dd hh:mm:ss", 
CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out odate);

最新更新