具有不同文化的日期时间值不正确格式化 [英] Datetime value with different culture not formatting correctly

查看:187
本文介绍了具有不同文化的日期时间值不正确格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在线文化遇到一个小问题,并得到日期显示正确。
我正在重载DateTime类的ToString()方法。

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.

使用文化en-CA,我的日期以正确的格式出现 yyyy / MM / dd
但与文化fr-CA,我的日期正在出来yyyy-MM-dd

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.

即使我更改了GetDateInStringMethod来做.ToShortDateString。我仍然遇到同样的问题。

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


推荐答案

这不行,因为使用法语文化默认datetime格式化程序使用 - 而不是 / 作为分隔符。

如果您希望保持日期相同,无论文化如何,请使用 CultureInfo.InvariantCulture

如果要使用法语格式化您所期望的更改测试结果为2009-02-07

如果您正在寻找更多信息,请检查这个msdn链接


如果你想要一个lib的个人推荐用于处理全球化的真棒,那么我建议 Noda Time

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.

这篇关于具有不同文化的日期时间值不正确格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆