DateTime.ToString 和 DateTime.ParseExact 之间的日期时间格式不一致
这很好奇。例如,当我运行时,
DateTime.Now.ToString("dd/MM/yyyy")
结果是
"22-02-2022"
注意我请求斜杠分隔符,而不是连字符分隔符。然而,我想这是一个控制面板定义,尽管我认为它不应该。
好吧......现在,我尝试做相反的事情,将字符串转换为日期,所以我使用了这个,
DateTime.ParseExact("22-02-2022", "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture, System.Globalization.DateTimeStyles.None)
之后,抛出了 FormatException
。
为了保持一致,我认为如果对于系统来说,连字符是分隔符,那么在两个方向转换时,分隔符应该是相同的,不是吗?
当然,如果我使用的话,
DateTime.ParseExact("22/02/2022", "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture, System.Globalization.DateTimeStyles.None)
它会起作用。
作为解决方法,我在将字符串转换为日期之前用斜杠替换连字符,但这只是一个丑陋的解决方法。有没有办法让系统保持一致?
海梅
this is very curious. When I run, for example,
DateTime.Now.ToString("dd/MM/yyyy")
Result is
"22-02-2022"
Notice that I requested a slash separator, not hyphen separator. However, I guess this is a control panel definition although I think it shouldn't.
Well.... now, I try to do the contrary, converting a string to a date, so I used this,
DateTime.ParseExact("22-02-2022", "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture, System.Globalization.DateTimeStyles.None)
After that, a FormatException
is thrown.
To be consistent, I think if for the system, a hyphen is the separator, when converting in both directions, that separator should be the same, shouldn't it?
Of course, if I use,
DateTime.ParseExact("22/02/2022", "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture, System.Globalization.DateTimeStyles.None)
It works.
As a workaround, I replace hyphens by slashes before converting string to date, but that is only an ugly workaround. Is there a way to make the system be consistent?
Jaime
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能会看到该问题,因为计算机的区域/本地化设置不使用
/
作为日期分隔符。“/”自定义格式说明符表示:
进而:
您有几个选项可以输出所需的分隔符:
ToString
时使用CultureInfo.InvariantCulture
:这两者都应生成格式为
dd/MM/yyyy
的日期,并使用“/”作为分隔符。演示
It's likely you're seeing that issue because the region/localization settings of the machine doesn't use
/
as a date separator.The docs on the "/" custom format specifier says:
And then:
You have a couple of options to output the desired separator:
CultureInfo.InvariantCulture
when callingToString
:Both of these should produce a date in the format
dd/MM/yyyy
using "/" for the separator.Demo