Dot-Net

為什麼 DateTime.ToShortTimeString() 不尊重“區域和語言設置”中的短時間格式?

  • May 25, 2013

我遇到了一個問題,這可能是由於我對 DateTime.ToShortTimeString() 方法的工作原理有誤解。使用此函式格式化時間字元串時,我假設它會尊重 Windows 7 格式設置中的“短時間”設置

控制面板 -> 時鐘、語言和區域 -> 區域和語言 -> 格式選項卡。

然而 .NET 似乎選擇了一種短時間格式,而不是基於此設置,而是基於目前文化:

地區和語言 -> 位置 -> 目前位置

我在 Windows 7 RC 上做了一些測試:

文化:en-GB,早上 6 點:06:00,下午 6 點:18:00 // HH:mm(英國)
文化:en-GB,早上 6 點:06:00,下午 6 點:18:00 // hh:mm(英國)
文化:en-US,6AM:6:00 AM,6PM:6:00 PM // HH:mm(美國)
文化:en-US,6AM:6:00 AM,6PM:6:00 PM // hh:mm(美國)
文化:el-GR,6AM:6:00 am,6PM:6:00 pm // HH:mm(希臘)
文化:el-GR,6AM:6:00 am,6PM:6:00 pm // hh: mm(希臘)

我使用了 el-GR,因為這是報告問題的使用者的文化,他還在 Vista SP2 和 Win 7 RC 上進行了測試,結果相同。

問題實際上有兩個方面:1)我對 .NET 和 Windows 格式的誤解是什麼?2)基於作業系統創建短格式時間字元串(HH:mm或hh:mm tt)的最佳解決方案是什麼,理想情況下這應該在Mono中工作,所以我寧願避免從系統資料庫或P / Invoke讀取.

上面用來生成的方法,供以後參考和測試。

[STAThread]
static void Main(string[] args)
{
   CultureInfo culture = CultureInfo.CurrentCulture;

   DateTime sixAm = new DateTime(2009, 07, 05, 6, 0, 0); // 6AM 
   DateTime sixPm = new DateTime(2009, 07, 05, 18, 0, 0); // 6PM

   string sixAmString = sixAm.ToShortTimeString();
   string sixPmString = sixPm.ToShortTimeString();

   string format = "Culture: {0}, 6AM: {1}, 6PM: {2}";

   string output = String.Format(format, culture, sixAmString, sixPmString);
   Console.WriteLine(output);
   Clipboard.Clear();
   Clipboard.SetText(output);

   Console.ReadKey();
}

更新: 根據 Mike 在下面的評論,我對上述方法進行了以下更改:

以下兩行

string sixAmString = sixAm.ToShortTimeString();
string sixPmString = sixPm.ToShortTimeString();

變成

string sixAmString = sixAm.ToString("t", culture);
string sixPmString = sixPm.ToString("t", culture);

我還將文化變數更改為使用 CultureInfo.CurrentUICulture。

不幸的是,這並沒有像我希望的那樣工作,無論 Windows 7 格式選項卡中的短時間配置如何,輸出都是:

文化:美國,上午 6 點:上午 6:00,下午 6 點:下午 6:00

似乎 CultureInfo.CurrentUICulture 總是在美國。

你的第二個問題的答案是

DateTimeFormat.Format(DateTime.Now, "t", CultureInfo.CurrentUICulture);

或者

DateTime.Now.ToString("t", CultureInfo.CurrentUICulture);

實際上,使用接受 CultureInfo 的顯式方法總是更好。.Net 如何選擇預設使用 CurrentCulture 或 CurrentUICulture 或 InvarinatCulture 沒有一致性。

使答案完整。我還將概述文化之間的差異。

所以 CurrentCulture 是“控制面板 -> 時鐘、語言和區域 -> 區域和語言 -> 格式選項卡”。這是您期望您的計算成為的文化。例如,您可以在美國進行會計,因此您必須在美國進行配置。

CurrentUICulture 是“區域和語言 -> 顯示語言”,意味著當您從烏克蘭移民時,您希望您的應用程序在 UA 本地化(但所有計算仍在美國)。

InvariantCulture 就是所謂的與文化無關的語言環境。您應該使用它來儲存資訊等。實際上它是 En-US。

注意:我可能錯了每個設置位於 Windows 中的位置。但你可能有一個想法。

我很確定在 DateTime.ToShortTimeString() 或 DateTime.ToString(“t”) 中未使用短時間格式字元串這一事實是一個錯誤,因為它已在 .NET Framework 4.0 中修復。

引用自:https://stackoverflow.com/questions/1292246