Search code examples
datetimeasp.net-mvc-5utccultureinfolocaltime

Convert DateTime with a specified language


I am coding a MVC 5 internet application and am wanting to convert a DateTime to be displayed as a LocalTime where I have the language. This is for an Azure website.

Here is my code:

DateTime dateTimeUtcNow = DateTime.UtcNow;
DateTime convertedDate = DateTime.SpecifyKind(dateTimeUtcNow, DateTimeKind.Utc);
DateTime dateTimeLocalTime = convertedDate.ToLocalTime();
return dateTimeLocalTime.ToString(new CultureInfo("en-NZ"));

The output from the above code is the exact same output as if I return the DateTime in UTC with no language culture specified.

How can I convert a DateTime in UTC for a local time where I have the culture language?

Thanks in advance.


Solution

  • 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 NewZ ealand English:

    CultureInfo enAU = new CultureInfo("en-NZ");
    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;
      }
    

    You may also want to look at the overloaded tryParse method if you need to parse the string against a particular language/culture...