[英]Datetime value with different culture not formatting correctly
我在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";
更改此行:
return obj.Value.ToString(Utility.DatePattern);
對此:
return obj.Value.ToString(Utility.DatePattern, CultureInfo.InvariantCulture);
在此處閱讀有關內容: System.Globalization.InvariantCulture
這是行不通的,因為使用法語文化默認將日期時間格式設置為-
而不是/
作為分隔符。
如果您希望無論文化如何都保持相同的日期,請使用CultureInfo.InvariantCulture
如果要使用法語格式,請將您的預期測試結果更改為"2009-02-07"
。
如果您正在尋找更多信息,請檢查此msdn鏈接 。
而且,如果您希望針對lib提出個人建議以應對全球化這一令人敬畏的事情,那么我建議Noda Time 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.