Skip to main content
 首页 » 编程设计

c#之DateTime.Parse Extract 的参数不正确问题

2024年02月13日22zdz8207

我有以下一行。 DateTime.ParseExact("08-11-2013 07:38:05", "yyyy-MM-dd HH:mm:ss", Nothing)

它抛出一个错误。

参数不正确。

堆栈跟踪

at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style) at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)

提前致谢。

请您参考如下方法:

您的格式与您提供的日期不匹配,应该是:

"dd-MM-yyyy HH:mm:ss" 

考虑到您的意思是 2013 年 11 月 8 日

你的代码应该是:

DateTime dt = DateTime.ParseExact("08-11-2013 07:38:05",  
                                  "dd-MM-yyyy HH:mm:ss",  
                                   CultureInfo.InvariantCulture); // Instead of Nothing 

您还可以使用 "d-M-yyyy HH:mm:ss" 格式,因为它会同时考虑一位数/两位数的日期和月份。

此外您似乎来自 VB.Net 背景,其中 Nothing 是默认值,在 C# 中您可以使用 null对于您的情况或更好地使用 CultureInfo.InvariantCulture

有关更多信息,请参阅:Custom Date and Time Format Strings