我遇到了一个问题,这可能是由于我对 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,早上 6 点:6:00 πμ,下午 6 点:6:00 μμ // HH:mm(希腊) 文化:el-GR,早上 6 点:6:00 πμ,下午 6 点:6:00 μμ // 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 总是在美国。