gpt4 book ai didi

c# - 在 DateTime.ParseExact 中将不变文化与 IFormatProvider 结合使用

转载 作者:行者123 更新时间:2023-11-30 21:33:02 27 4
gpt4 key购买 nike

在 ParseExact 方法的第一次重载中

public static DateTime ParseExact (string s, string format, IFormatProvider provider);

根据微软的说法:

If format is a custom format pattern that does not include date or time separators (such as "yyyyMMddHHmm"), use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the format pattern, specify the wider form, "HH", instead of the narrower form, "H".

特别是如果我们使用标准格式模式,我们可以使用任何其他文化

如果我们使用不包含日期或时间分隔符的自定义格式模式,那么使用不变文化和最宽自定义说明符的真正目的是什么?

最佳答案

InvariantCulture 的目的是采用一种不依赖于系统或用户区域设置的众所周知的方式来格式化日期和数字。

每次格式化不打算由人类解析的内容时,您都应该使用它。例如,在 JSON 或 XML 文件中,您希望以 ISO 格式存储日期,这样就不会出现歧义。另一方面,如果您在屏幕上显示日期,您通常会尊重用户的文化选择并以首选方式显示。


如果您使用自定义格式,那么如果可以将生成的字符串解析回完全相同的日期和时间,那肯定会很好。为了在没有分隔符的情况下做到这一点,您必须为每个组件使用固定长度的字符串。

// omitting CultureInfo.InvariantCulture for brevity
var dt = new DateTime(2018,1,2,3,45,6);
dt.ToString("yyyyMMddHHmmss") // returns "20180102034506"
dt.ToString("yyyyMdHms") // returns "2018123456"

您可以很容易地看出第二个不是唯一的,即还有其他日期将返回相同的字符串。为了避免您使用每个组件的更宽形式。

关于c# - 在 DateTime.ParseExact 中将不变文化与 IFormatProvider 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51820648/

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