简体   繁体   English

如何使用 CultureInfo 生成本地化日期字符串

[英]How to produce localized date string with CultureInfo

I have the following code that produces a date string in en-us format.我有以下代码以 en-us 格式生成日期字符串。 I would like to pass in the LCID (or equivalent value for the localized language) to produce the localized version of the date string.我想传入 LCID(或本地化语言的等效值)以生成日期字符串的本地化版本。 How would I accomplish this?我将如何做到这一点?

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

You can use the second argument to the toString function and use any language/culture you need...您可以使用toString函数的第二个参数并使用您需要的任何语言/文化......

You can use the "d" format instead of ToShortDateString according to MSDN...根据 MSDN,您可以使用“d”格式而不是ToShortDateString ......

So basically something like this to return as Australian English:所以基本上像这样返回澳大利亚英语:

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

you could modify your method to include the language and culture as a parameter您可以修改您的方法以包含语言和文化作为参数

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

Edit编辑
You may also want to look at the overloaded tryParse method if you need to parse the string against a particular language/culture...如果您需要针对特定​​语言/文化解析字符串,您可能还想查看重载的 tryParse 方法...

Use an overload of ToString() instead of a ToShortDateString() method.使用ToString()的重载而不是ToShortDateString()方法。 Supply an IFormatProvider .提供IFormatProvider

This should be helpful in forming a specific date-time string:这应该有助于形成特定的日期时间字符串:

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

This should be helpful with localization issues:这应该有助于解决本地化问题:

How do you handle localization / CultureInfo 你如何处理本地化/CultureInfo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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