C# Cultures: Localize DayOfWeek?
Asked Answered
L

2

40

How do I localize a DayOfWeek other than today?
The following works just fine for the current day:

DateTime.Now.ToString("dddd", new CultureInfo("it-IT"));

But how can I localize all days of the week??

Edit: A possible (and probably very, very wrong) solution I came up with could be to create DateTime values for an entire week, and then use date.ToString("dddd", new CultureInfo("it-IT")); on them, but that just seems wrong on so many levels.

Lapidate answered 31/5, 2011 at 2:24 Comment(0)
D
91

How about

DateTimeFormatInfo.CurrentInfo.GetDayName( dayOfWeek )

or

DateTimeFormatInfo.CurrentInfo.GetAbbreviatedDayName( dayOfWeek )

Simply takes a DayOfWeek enumeration and returns string that is the name in the current culture.

Edit:

If you're looking for a specific culture it would be

var cultureInfo = new CultureInfo( "it-IT" );
var dateTimeInfo = cultureInfo.DateTimeFormat;

then you can call GetDayName or GetAbbreviatedDayName as you choose.

There's even a AbbreviatedDayNames/DayNames arrays if you want them all

Durant answered 31/5, 2011 at 2:37 Comment(2)
Can you clarify please. If I serialised a DayOfWeek e I’m to XML and the user changes the pc locale , will this affect how the day is saved / read? Eg if it has Monday in xml and now pc is Spanish will it still know that Monday is Lunes? Does the xml internally always serialise with English days of week? I am not in a position to test but my app is in 50+ languages so it is an area of concern.Gabriella
@AndrewTruckle How XML serializes a day of the week will depend on your serialization library, configuration, and what code you've written. Use the InvariantCulture for serialization, see learn.microsoft.com/en-us/dotnet/api/…Durant
M
1

In addition to MerickOWA's answer, we can now create extension methods:

public static class DayOfWeekExtensions
{
    public static string GetDayName(this DayOfWeek value)
    {
        return DateTimeFormatInfo.CurrentInfo.GetDayName(value);
    }

    public static string GetAbbreviatedDayName(this DayOfWeek value)
    {
        return DateTimeFormatInfo.CurrentInfo.GetAbbreviatedDayName(value);
    }
}
Marriage answered 21/7, 2022 at 2:38 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.