【发布时间】:2013-02-07 13:55:31
【问题描述】:
我在 Thread 文化和获取正确显示的日期方面遇到了一点问题。 我正在重载 DateTime 类的 ToString() 方法。
使用文化“en-CA”,我的日期以正确的格式“yyyy/MM/dd”出来 但是文化是“fr-CA”,我的约会对象是“yyyy-MM-dd”
我进行了一些单元测试来显示问题。 英语测试有效,但法语总是失败。
即使我将 GetDateInStringMethod 更改为 .ToShortDateString。我仍然遇到同样的问题。
[Test()]
public void ValidInEnglish()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = Utility.DatePattern;
DateTime? currentDate = new DateTime(2009,02,7);
string expected = "2009/02/07";
string actual = DateUtils.GetDateInString(currentDate);
//This works
Assert.AreEqual(expected, actual);
}
[Test()]
public void ValidInFrench()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-CA");
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = Utility.DatePattern;
DateTime? currentDate = new DateTime(2009, 02, 7);
string expected = "2009/02/07";
string actual = DateUtils.GetDateInString(currentDate);
// This doesn't work
Assert.AreEqual(expected, actual);
}
public static string GetDateInString(DateTime? obj)
{
if (obj == null || !obj.HasValue)
{
return string.Empty;
}
return obj.Value.ToString(Utility.DatePattern);
}
public const string DatePattern = "yyyy/MM/dd";
【问题讨论】:
标签: c# datetime localization cultureinfo