繁体   English   中英

具有不同区域性的日期时间值格式不正确

[英]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.

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