【问题标题】:How to produce localized date string with CultureInfo如何使用 CultureInfo 生成本地化日期字符串
【发布时间】:2011-08-13 12:33:59
【问题描述】:

我有以下代码可以生成 en-us 格式的日期字符串。我想传入 LCID(或本地化语言的等效值)来生成日期字符串的本地化版本。我将如何做到这一点?

public static string ConvertDateTimeToDate(string dateTimeString) {

    CultureInfo culture = CultureInfo.InvariantCulture;
    DateTime dt = DateTime.MinValue;

    if (DateTime.TryParse(dateTimeString, out dt))
    {
        return dt.ToShortDateString();
    }
    return dateTimeString;
  }

【问题讨论】:

    标签: c# .net datetime cultureinfo


    【解决方案1】:

    使用ToString() 的重载而不是ToShortDateString() 方法。提供IFormatProvider

    这应该有助于形成特定的日期时间字符串:

    http://www.csharp-examples.net/string-format-datetime/

    这应该有助于解决本地化问题:

    How do you handle localization / CultureInfo

    【讨论】:

    • 感谢您提供上述示例。它们对于为我们不同的国际语言格式化日期字符串非常有帮助。
    • 我刚刚尝试投票,但看起来我需要 15 声望才能投票。抱歉,我仍然是 StackOverflow 的菜鸟。 :-|
    【解决方案2】:

    您可以使用 toString 函数的第二个参数并使用您需要的任何语言/文化...

    根据 MSDN,您可以使用“d”格式而不是 ToShortDateString...

    所以基本上像这样以澳大利亚英语返回:

    CultureInfo enAU = new CultureInfo("en-AU");
    dt.ToString("d", enAU);
    

    您可以修改方法以将语言和文化作为参数包含在内

    public static string ConvertDateTimeToDate(string dateTimeString, String langCulture) {
    
        CultureInfo culture = new CultureInfo(langCulture);
        DateTime dt = DateTime.MinValue;
    
        if (DateTime.TryParse(dateTimeString, out dt))
        {
            return dt.ToString("d",culture);
        }
        return dateTimeString;
      }
    

    编辑
    如果您需要针对特定​​语言/文化解析字符串,您可能还想查看overloaded tryParse method...

    【讨论】:

    • 谢谢。上面的代码有效。是的,我将传入语言代码作为参数,以生成各种国际语言的本地化日期字符串。
    • 我问的有点晚,但是你有 MSDN 参考吗?
    • @Steve 我认为这只是为了举例。我们不限于d 格式。如果某人想使用另一种格式,我会让以下文章供参考:Custom date and time format strings
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    相关资源
    最近更新 更多