How to produce localized date string with CultureInfo
Asked Answered
H

2

32

I have the following code that produces a date string in en-us format. I would like to pass in the LCID (or equivalent value for the localized language) to produce the localized version of the date string. 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;
  }
Haws answered 27/4, 2011 at 3:8 Comment(0)
I
63

You can use the second argument to the toString function and use any language/culture you need...

You can use the "d" format instead of ToShortDateString according to MSDN...

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...

Irrevocable answered 27/4, 2011 at 3:24 Comment(3)
Thank you. The above code works. And yes, I'll be passing in language codes as parameters to produce localized date strings for various international languages.Haws
A bit late for me to ask, but do you have the MSDN Reference?Phlegm
@Phlegm I think it was just for example purposes. We aren't limited to the d format. And if sb wants to use another format I'll let the following article for reference: Custom date and time format stringsVidovic
E
6

Use an overload of ToString() instead of a ToShortDateString() method. Supply an IFormatProvider.

This should be helpful in forming a specific date-time string:

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

This should be helpful with localization issues:

How do you handle localization / CultureInfo

Epizoon answered 27/4, 2011 at 3:23 Comment(2)
Thank you for the examples above. They will be very helpful at formatting the date strings for our different international languages.Haws
I just tried to upvote, but it looks like I need 15 Reputation to Vote Up. Sorry, I'm still a noob at StackOverflow. :-|Haws

© 2022 - 2024 — McMap. All rights reserved.