简体   繁体   中英

Datetime value with different culture not formatting correctly

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM