解析具有单个数字日的日期字符串,例如1-11-2017以及12-11-2017

Sen*_*alk 1 c# datetime

所以我有一个日期字符串与今天的短日期.例如"1-11-2017"

//Here i convert the HttpCookie to a String 
string DateView = Convert.ToString(CurrDay.Value);

//Here i convert the String to DateTime
DateTime myDate = DateTime.ParseExact(DateView, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)

运行代码后,我收到错误:

FormatExeption未被用户代码处理

mscorlib.dll中出现"System.FormatException"类型的异常,但未在用户代码中处理

附加信息:字符串未被识别为有效的DateTime.

Igo*_*gor 7

1-11-2017不是格式dd-MM-yyyy,特别是第一部分.使用d-M-yyyy,而不是将使用一个数字日期和月份当值低于10(即无0填充).

测试:

DateTime myDate = DateTime.ParseExact("1-11-2017", "d-M-yyyy", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(myDate.ToString());
Run Code Online (Sandbox Code Playgroud)

如果您不知道是否存在0填充,则可以传递可接受格式的数组,解析器将尝试每个填充,以便它们出现在数组中.

DateTime myDate = DateTime.ParseExact("1-11-2017", new string[]{"d-M-yyyy", "dd-MM-yyyy"}, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
Run Code Online (Sandbox Code Playgroud)

小提琴


Sen*_*alk 2

我使用 yyyy-MM-dd 而不是 dd-MM-yyyy 解决了这个问题(然后将其转换为正常日期)因为 var 始终是今天的日期,该日期可以是 1 和 2 位数字

 CurrDay.Value = DateTime.Now.ToString("yyyy-MM-dd" ); 

 // Convert String to DateTime
 dateFrom = DateTime.ParseExact(CurrDay.Value.ToString(), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)

下面的评论帮助我找到了这个解决方案,谢谢大家!