Datetime value with different culture not formatting correctly

…衆ロ難τιáo~ 提交于 2019-12-24 08:49:57

问题


I'm having a slight issue with Thread culture and getting a date to display properly. I am overloading the ToString() method of the DateTime class.

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"

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. 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";

回答1:


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

if you want to use the french formatting the change your expected test result to "2009-02-07".

If you are looking for more info check this msdn link.

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.




回答2:


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



来源:https://stackoverflow.com/questions/14752821/datetime-value-with-different-culture-not-formatting-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!