gpt4 book ai didi

c# - 用一位数的日期解析日期字符串,例如1-11-2017 以及 12-11-2017

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:48 24 4
gpt4 key购买 nike

所以我有一个日期字符串和今天的短日期。
例如“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);

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

FormatExeption was unhandled by user code

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

Additional information: String was not recognized as a valid DateTime.

最佳答案

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());

如果您不知道是否会有 0 填充,您可以传递一个可接受格式的数组,解析器将按照它们出现在数组中的顺序尝试每个格式。
DateTime myDate = DateTime.ParseExact("1-11-2017", new string[]{"d-M-yyyy", "dd-MM-yyyy"}, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);

Fiddle

关于c# - 用一位数的日期解析日期字符串,例如1-11-2017 以及 12-11-2017,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47052779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com