gpt4 book ai didi

c# - 为什么 DateTime.ParseExact 不适用于美国以外的这个示例?

转载 作者:行者123 更新时间:2023-11-30 13:55:16 25 4
gpt4 key购买 nike

我有一个字符串:

var stringDate = "8/19/2016 5:00:00 PM"

我尝试使用:

var dateTime = DateTime.ParseExact(stringDate,"M/d/yyyy h:mm:ss tt", null);

var dateTime = DateTime.ParseExact(stringDate, "M/d/yyyy h:mm:ss tt", 
CultureInfo.Invariant);

var dateTime = DateTime.ParseExact(stringDate,"M/d/yyyy h:mm:ss tt",
CultureInfo.GetCultureInfo("en-us"));

如果机器在美国,它工作正常,但是对于所有 3 个选项,当从伦敦的机器运行时,我收到以下错误:

String was not recognized as a valid DateTime

我在这里错过了什么?

最佳答案

据我所知,您需要使用 h specifier而不是 hh specifier因为您的小时部分没有单个数字值的前导零。

var stringDate = "8/19/2016 5:00:00 PM";
var dateTime = DateTime.ParseExact(stringDate, "M/d/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture);

enter image description here

此外,我建议在任何情况下都使用特定 区域性设置而不是null。在您的示例中,由于 null 表示 DateTime 解析方法的 CurrentCulture 设置,您的 CurrentCulture 设置;

对于那些,如果您的字符串和格式完全匹配,您的 ParseExact 方法将抛出异常甚至

关于c# - 为什么 DateTime.ParseExact 不适用于美国以外的这个示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35957654/

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