格式化DateTime而不覆盖C#中的CultureInfo

本文关键字:中的 CultureInfo 覆盖 DateTime 格式化 | 更新日期: 2023-09-27 18:27:35

在C#中,如何使用DateTime格式字符串来控制显示日期的哪些部分,同时不覆盖CultureInfo?

System.Globalization.CultureInfo cultureInfoUS = new System.Globalization.CultureInfo("en-US", false);
System.Globalization.CultureInfo cultureInfoGerman = new System.Globalization.CultureInfo("de-DE", false);
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfoUS;
DateTime date = DateTime.Parse("03-13-2012 01:30:00 PM");
Console.WriteLine(date.ToString(cultureInfoGerman));
//produces 13.03.2012 13:30:00
Console.WriteLine(date.ToString("MM/dd/yyyy", cultureInfoGerman));
//produces 03.13.2012 but should be 13.03.2012
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfoGerman;
Console.WriteLine(date.ToShortTimeString());
//produces: 13:30
Console.WriteLine(date.ToString("h:mm tt", cultureInfoGerman));
//produces: 1:30 but should be 13:30
Console.WriteLine(date.ToString("h:mm tt", cultureInfoUS));
//produces: 1:30 PM

您可以在上面的代码中看到注释。CultureInfo会对输出进行部分调整,但不会完全调整。

此外,ToShortDateStringToShortTimeString方法不采用IProvider,因此必须依赖于当前线程的区域性信息。以上第一个示例对此进行了说明。是否期望您更改当前区域性,调用ToShortDateString,然后将线程恢复到原始区域性?

格式化DateTime而不覆盖C#中的CultureInfo

我不理解代码中的注释-您使用的自定义日期/时间格式说明符的行为与我预期的完全一样。为什么您希望"MM/dd/yyyy"将日期放在首位?

如果你想要一个基于给定区域性使用的模式的自定义格式,你可以通过查看DateTimeFormatInfo.ShortDatePatternDateTimeFormatInfo.ShortTimePattern等来构建它。例如,如果你想要以一周中的某一天为单位,然后是特定于区域性的短时间的自定义格式时,你可以使用:

string format = "dddd " + culture.DateTimeFormat.ShortTimePattern;
Console.WriteLine(DateTime.Now.ToString(format, culture);

是否期望您更改当前区域性,调用ToShortDateString,然后将线程还原回原始区域性?

不,如果您想要当前区域性以外的内容,则应该使用标准日期/时间格式字符串:

date.ToString("d", culture); // short date
date.ToString("t", culture); // short time