C# DateTime.TryParseExact不起作用-返回false,但应为true
我尝试用TryParseExact验证DateTime对象。任务是检查DateTime是否包含时间而不仅仅是日期。到目前为止,我拥有的代码:C# DateTime.TryParseExact不起作用-返回false,但应为true,c#,.net,C#,.net,我尝试用TryParseExact验证DateTime对象。任务是检查DateTime是否包含时间而不仅仅是日期。到目前为止,我拥有的代码: public bool validateDateAndTime(DateTime checkDateFormat) { checkDateFormat = new DateTime(2019, 02, 02, 23, 33, 21); DateTime checkOutDate; if(DateTime.TryPar
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 case之前设置了“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);
hh
12小时还是24小时?为什么你要验证一个你已经知道是有效的日期?此外,此代码不安全。如果要在某个日期执行ToString
,则应具体说明格式,因为该格式的输出将根据主机系统的区域性而变化。“yyyy-MM-dd HH:MM:ss”
因为HH
是12小时格式如果只想检查datetime是否设置了小时/分/秒-值,简单比较一下:如果(date.Hour>0)…你介意解释一下投票结果吗。这正是原因。