[英]Datetime value with different culture not formatting correctly
I'm having a slight issue with Thread culture and getting a date to display properly. 我在Thread文化方面有一个小问题,并获取日期以正确显示。 I am overloading the ToString() method of the DateTime class.
我正在重载DateTime类的ToString()方法。
With culture "en-CA", my date is coming out in the right format "yyyy/MM/dd" but with culture "fr-CA", my date is coming out "yyyy-MM-dd" 使用文化“ en-CA”,我的日期以正确的格式“ yyyy / MM / dd”显示,但是使用文化“ fr-CA”,我的日期则以“ yyyy-MM-dd”显示
I've made some unit test to display the issue. 我已经进行了一些单元测试以显示问题。 The english test works but the french always fails.
英语测试有效,但法语总是不及格。
Even if I change the GetDateInStringMethod to do .ToShortDateString. 即使我将GetDateInStringMethod更改为.ToShortDateString。 I still get the same issue.
我仍然遇到同样的问题。
[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";
Change this line: 更改此行:
return obj.Value.ToString(Utility.DatePattern);
to this: 对此:
return obj.Value.ToString(Utility.DatePattern, CultureInfo.InvariantCulture);
Read about it here: System.Globalization.InvariantCulture 在此处阅读有关内容: System.Globalization.InvariantCulture
That doesn't work because using french culture defaults the datetime formatter to use -
instead of /
as a separator character. 这是行不通的,因为使用法语文化默认将日期时间格式设置为
-
而不是/
作为分隔符。
If you want to keep your date the same no matter the culture then use CultureInfo.InvariantCulture
如果您希望无论文化如何都保持相同的日期,请使用
CultureInfo.InvariantCulture
if you want to use the french formatting the change your expected test result to "2009-02-07"
. 如果要使用法语格式,请将您的预期测试结果更改为
"2009-02-07"
。
If you are looking for more info check this msdn link . 如果您正在寻找更多信息,请检查此msdn链接 。
And if you want a personal recommendation for a lib to use for dealing with the awesomeness that is Globalization then I'd recommend Noda Time . 而且,如果您希望针对lib提出个人建议以应对全球化这一令人敬畏的事情,那么我建议Noda Time 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.