【问题标题】:Change month names that are returned from ToString("MMMM") to own names将 ToString("MMMM") 返回的月份名称更改为自己的名称
【发布时间】:2017-02-20 20:55:28
【问题描述】:

使用以下代码,我在 de-CH 文化中得到以下结果:

var dateFormat = new DateTime(2016, 10, 12).ToString("MMMM");
//Oktober

虽然我真正想要的是“Oktobär”,因为我正在翻译方言。

我可以覆盖在 de-CH 文化中返回的月份名称吗?它为其他文化返回的名称应该保持不变。

【问题讨论】:

  • 瑞士德语没有正式的拼写规则。因此,您无法通过将其更改为去 CH 文化来实现这一目标。
  • @diiN_ 是的,我知道。
  • 您可以为CultureInfo 的一个特定实例更改它(请参阅DateTimeFormatInfo.MonthNames),但这不会改变如果您再次获取de-CH 文化会发生什么。您是否总是使用那种特定的文化?如果是这样,您可以将其传递给所有 ToString/Format 调用。

标签: c# asp.net-mvc datetime


【解决方案1】:
CultureInfo myCIclone = new CultureInfo("de-CH");

myCIclone.DateTimeFormat.MonthNames = new string[]
{"1","2","3","4","5","6","7","8","9","Oktobär","11","12", "13"};

var dateFormat = new DateTime(2016, 10, 12).ToString("MMMM", myCIclone);

您可以像提到的 John Skeet 一样覆盖 MonthNames,以获取特定的文化信息。

【讨论】:

  • 如果在当前线程上设置了修改后的区域性,则不需要将其指定为ToString方法的第二个参数。
  • 谢谢,这按预期工作!我在有关 DateTimeFormat.MonthNames 的文档中读到了这一点:If you set the MonthNames property, you must also set the MonthGenitiveNames property. 这些将用于什么?我不明白 MonthGenetiveNames 属性中添加的备注:In some languages, a month name that is part of a date appears in the genitive case. For example, a date in the Russian (Russia) or "ru-RU", culture consists of the day number and the genitive month name, such as 1 Января.
  • @Marimba 据我了解,这是针对该语言的语法情况。大多数西里尔语言都有这个,这意味着根据上下文,月份名称会有所不同。所以如果你的语言有属格语言,你也应该覆盖它。
  • @mybirthname 啊。现在我明白了!
【解决方案2】:

这可能对您有帮助。您需要覆盖默认值。

//Declare Culture Info with your goblaization name.
CultureInfo culture = new CultureInfo("de-CH");

//Assign needed value.
culture.DateTimeFormat.MonthNames = new string[]{"1","2","3","4","5","6","7","8","9","Oktobär","11","12", "13"};

//Assign it in string.
string date= new DateTime(2016, 10, 12).ToString("MMMM", culture);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    相关资源
    最近更新 更多