如何使用 Dateformat ISO 8601 创建 .NET CultureInfo?

How to create .NET CultureInfo with Dateformat ISO 8601?

是否可以让 .NET 创建以下输出?

DateTime.UtcNow.ToString() --> "2017-11-07T00:40:00.123456Z"

当然总是可以使用 ToString("s") 或 ToString("yyyy-MM-ddTHH:mm:ss.fffffffK")。但是有没有办法将无参数 ToString-Method 的默认行为调整为所需的输出?

我尝试更改 CurrentCulture。但我得到的最好的是“2017-11-07 00:40:00.123456Z”。我没有找到将日期和时间之间的分隔符从 space 更改为 "T" 的方法。

这是可能的,但只能通过反射访问内部字段,不能保证在所有情况下都有效。

var culture = (CultureInfo) CultureInfo.InvariantCulture.Clone();
var field = typeof(DateTimeFormatInfo).GetField("generalLongTimePattern",
                                           BindingFlags.NonPublic | BindingFlags.Instance);
if (field != null)
{
    // we found the internal field, set it
    field.SetValue(culture.DateTimeFormat, "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK");
}
else
{
    // fallback to setting the separate date and time patterns
    culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
    culture.DateTimeFormat.LongTimePattern = "HH:mm:ss.FFFFFFFK";
}
CultureInfo.CurrentCulture = culture;

Console.WriteLine(DateTime.UtcNow);  // "2017-11-07T00:53:36.6922843Z"

请注意,ISO 8601 规范 允许使用 space 而不是 T最好使用T

斯科特·汉塞尔曼 (Scott Hanselmann) 已就此发表博客 here

a little Reflectoring shows us that the default format string for System.DateTime is "G" as in System.DateTime.ToString("G") where G is one of the presets.

[...]

And gets the output he expects, indicating that "G" is the combination of a ShortDate and a LongTime.

所以你应该覆盖 ShortDatePatternLongTimePattern:

我将代码转换为 C#,是的,它正在运行:

var customCulture = new CultureInfo("en-US")
{
    DateTimeFormat =
    {
        ShortDatePattern = "yyyy-MM-dd",
        LongTimePattern = "HH:mm:ss.FFFFFFFK"
    }
};

Console.WriteLine(DateTime.Now);

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;
Console.WriteLine(DateTime.Now);

Console.ReadLine();

然而,Scott 将他的 post Enabling Evil 命名为有原因的。做之前请三思!

T不需要,也无法提供。如果你还需要它,你需要使用Reflection,如.