31

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;
  }
GregC
  • 7,737
  • 2
  • 53
  • 67
Keith
  • 1,959
  • 10
  • 35
  • 46

2 Answers2

62

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

davidsleeps
  • 9,393
  • 11
  • 59
  • 73
  • 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. – Keith Apr 27 '11 at 04:46
  • A bit late for me to ask, but do you have the MSDN Reference? – Steve Jun 06 '15 at 00:16
  • @Steve 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 strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings) – richardsonwtr Aug 05 '20 at 12:54
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

Dale K
  • 25,246
  • 15
  • 42
  • 71
GregC
  • 7,737
  • 2
  • 53
  • 67
  • Thank you for the examples above. They will be very helpful at formatting the date strings for our different international languages. – Keith Apr 27 '11 at 05:01
  • 1
    I just tried to upvote, but it looks like I need 15 Reputation to Vote Up. Sorry, I'm still a noob at StackOverflow. :-| – Keith Apr 27 '11 at 05:31