Loop week based on culture info
How do I loop the whole week (monday-sunday) based on culture info, so in my case monday will be the first day of the week? And is it possible to find the int
value of the day at the same time开发者_运维百科?
For some information: I need to make this in order to make some generel opening hours for a store.
I think what you need is the following loop.
DayOfWeek firstDay = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
for (int dayIndex = 0; dayIndex < 7; dayIndex++)
{
var currentDay = (DayOfWeek) (((int) firstDay + dayIndex) % 7);
// Output the day
Console.WriteLine(dayIndex + " " + currentDay);
}
The modulo 7 is important, because the firstdayofweek can vary by different cultures.
This would give you the first day of the week in a given culture.
DayOfWeek firstDay = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
this could subsequently be...
int firstDay = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
DayOfWeek.Sunday = zero
DayOfWeek.Saturday = 6
You would iterate it like any other int.
http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx
DateTime Dt = new DateTime(2011,5,13,0,0,0);
int WeeklyOffValue = (int)Dt.DayOfWeek
The Time Period Library for .NET includes the class Week with support of the culture:
// ----------------------------------------------------------------------
public void WeekDaysSample()
{
Week week = new Week( new DateTime( 2011, 05, 13 ) );
foreach ( Day day in week.GetDays() )
{
Console.WriteLine( "Day: {0}, DayOfWeek: {1}, Int: {2}", day, day.DayOfWeek, (int)day.DayOfWeek );
// > Day: Montag; 09.05.2011 | 0.23:59, DayOfWeek: Monday, Int: 1
// > Day: Dienstag; 10.05.2011 | 0.23:59, DayOfWeek: Tuesday, Int: 2
// > Day: Mittwoch; 11.05.2011 | 0.23:59, DayOfWeek: Wednesday, Int: 3
// > Day: Donnerstag; 12.05.2011 | 0.23:59, DayOfWeek: Thursday, Int: 4
// > Day: Freitag; 13.05.2011 | 0.23:59, DayOfWeek: Friday, Int: 5
// > Day: Samstag; 14.05.2011 | 0.23:59, DayOfWeek: Saturday, Int: 6
// > Day: Sonntag; 15.05.2011 | 0.23:59, DayOfWeek: Sunday, Int: 0
}
} // WeekDaysSample
This works even today, Friday the 13th :)
for (int i = 1; i <= 7; i++)
Console.WriteLine(new DateTime(2014, 6, i).ToString("DDDD", culture));
July 1, 2014 - Sunday
I believe you want to loop through the weeks, something like this
foreach (DayOfWeek dy in Enum.GetValues(typeof(DayOfWeek)))
{
dy.ToString() // this would be Sunday, monday ......
}
精彩评论