[英]C# make DateTime.TryParse() NOT assume year
The DateTime.TryParse()
method in C# will assume current year if there's no year specified.如果没有指定年份,C# 中的DateTime.TryParse()
方法将采用当前年份。 I want a function that will return false
if the year is not specified (and not assume).我想要一个 function,如果没有指定年份(并且不假设),它将返回false
。
I cannot use DateTime.TryParseExact()
because I don't know the format - I want it to work in general just like DateTime.TryParse()
.我不能使用DateTime.TryParseExact()
因为我不知道格式 - 我希望它像DateTime.TryParse()
一样正常工作。
These test cases should return false
:这些测试用例应该返回false
:
"3/15"
"Dec 16,"
"4-11"
"Thursday Aug 6"
"Sept-9"
These test cases should return true
:这些测试用例应该返回true
:
"11/22/2016"
"Wed Jan 1, 2021"
"9-2-16"
"Aug.5.2018"
"2.28.1996"
You cannot parse unknown date format.您无法解析未知的日期格式。 The TryParseExact
is trying to parse a string to DateTime
with exact format. TryParseExact
正在尝试将字符串解析为具有精确格式的DateTime
。 I would suggest you to work with different formats you have specified like this我建议你使用你指定的不同格式
using System.Globalization;
var formats = new[] {"MM/dd/yyyy", "ddd MMM d, yyyy", "M-d-yy", "MMM.d.yyyy", "MM.dd.yyyy", "M.d.yyyy"};
foreach(var format in formats)
{
bool isValidDateTime = DateTime.TryParseExact(dateText, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out value);
if (isValidDateTime)
{
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.