Set language to Swedish
I h开发者_StackOverflowave this in my partial view:
<tr>
<% for (int currentDay = 0; currentDay < 7; currentDay++)
{ %>
<th>
<%= System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DayNames[currentDay] %>
</th>
<% } %>
</tr>
The weekday names render correctly in Swedish, but somehow the week starts with Sunday, while the first day of week in Sweden is Monday. How can I fix this?
And furthermore, is there some easy way to make it render first letter in weekday names as uppercase?
This isn't strange, the DayOfWeek enum is just defined as Sunday = 0. You have to do this by your own, using DateTimeFormatInfo.FirstDayOfWeek
in System.Globalization
.
Correct code would be:
CultureInfo ci = new CultureInfo("sv-SE");
int substraction = (int)ci.DateTimeFormat.FirstDayOfWeek;
int dayToGet = 0; //should return monday
var daynames = ci.DateTimeFormat.DayNames;
string day = daynames[dayToGet + substraction >= 7
? (dayToGet + substraction - 7) : dayToGet+substraction];
Dayname to upper depends on your culture setting, so I guess in Sweden it's all lower case, you can do str.Substring(0,1).ToUpper() + str.Substring(1)
, to get the first char up.
I think you miss understanding the purpose of DayNames. It will always start with "Sunday" or the appropriate language equivalent for "Sunday". Regardless of which culture is used.
Consider this code:-
string dayname = myCulture.DateTimeFormat.DayNames[myCulture.DateTimeFormat.FirstDayOfWeek]
What would you expect FirstDayOfWeek to be in the Swedish culture? Ans: 1
What would you expect to find in dayname? Ans: The swedish name for "Monday"
Hence you need element 1 for DayNames to be "Monday" and you'd expect the name previous to it at position 0 to be the name for "Sunday".
You could do something like this:
for (int currentDay = 0; currentDay < 7; currentDay++)
{
int currentLocalizedDay = ((int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek + currentDay) % 7;
Console.WriteLine(CultureInfo.CurrentCulture.DateTimeFormat.DayNames[currentLocalizedDay]);
}
Or changing your original code, to something like this:
<tr>
<% for (int currentDay = (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; currentDay < 7; currentDay = (currentDay + 1 % 7))
{ %>
<th>
<%= System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DayNames[currentDay] %>
</th>
<% } %>
</tr>
精彩评论