C# DateTime.ParseExact 不适用于特定日期

问题描述 投票:0回答:1

我正在尝试使用以下代码将包含事件日期和时间的字符串转换为 C# 中的 DateTime 对象:

...
try
{
    d = DateTime.ParseExact(date, "ddd MMM dd HH':'mm':'ss 'BST' yyyy", null);
}
catch (Format exception) {;}
...

当字符串“date”等于“Fri Oct 13 09:30:50 BST 2023”时,代码工作正常,但是当我将日期字符串设置为“Thu Sep 28 13:57:58 BST 2023”时,它会抛出以下例外:

System.FormatException: 'String 'Thu Sep 28 13:57:58 BST 2023' was not recognized as a valid DateTime.'

知道为什么会这样吗?

非常感谢。

c# datetime parsing
1个回答
0
投票

您只需要指定 CultureInfo 而不是 null

var date = "Thu Sep 28 13:57:58 BST 2023";
try
{
    var d = DateTime.ParseExact(date, "ddd MMM dd HH':'mm':'ss 'BST' yyyy", CultureInfo.InvariantCulture);                  
}
catch (Exception ex)
{

}

并且要小心,如果您指定了错误的星期缩写(例如“Fri Sep 28 13:57:58 BST 2023”),您将得到 System.FormatException

© www.soinside.com 2019 - 2024. All rights reserved.