在一個月內,我想知道星期一至sataurdays當月例如:在十月月2011有爲了讓週一至週六當月
3-oct-2011 to 8-oct-2011,
10-OCt-11 to 15-Oct-11,
17-Oct-11 to 22-oct-2011,
24-Oct-2011 to 29-Oct-2011
所有這些所有的這些日子天的序列像3-oct-2011,4-oct-2011 .... 29-oct-11等需要獲取數組格式或數據表。
在一個月內,我想知道星期一至sataurdays當月例如:在十月月2011有爲了讓週一至週六當月
3-oct-2011 to 8-oct-2011,
10-OCt-11 to 15-Oct-11,
17-Oct-11 to 22-oct-2011,
24-Oct-2011 to 29-Oct-2011
所有這些所有的這些日子天的序列像3-oct-2011,4-oct-2011 .... 29-oct-11等需要獲取數組格式或數據表。
var today = DateTime.Today;
var daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);
var dates = Enumerable.Range(1, daysInMonth)
.Select(n => new DateTime(today.Year, today.Month, n))
.Where(date => date.DayOfWeek != DayOfWeek.Sunday)
.ToArray();
這將看天當月的數量,爲每一個DateTime對象,然後只返回那些不是星期日作爲數組日期。
var today = DateTime.Today;
var daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);
var dates = Enumerable.Range(1, daysInMonth)
.Select(n => new DateTime(today.Year, today.Month, n))
.Where(date => date.DayOfWeek != DayOfWeek.Sunday)
.SkipWhile(date => date.DayOfWeek != DayOfWeek.Monday)
.TakeWhile(date => date.DayOfWeek != DayOfWeek.Monday || (date.DayOfWeek == DayOfWeek.Monday && daysInMonth - date.Day > 7))
.ToArray();
這樣做也是一樣,除非擺脫週一到週六不在本月的範圍。 (一週在前一個月開始,或在下一個月結束)。
編輯:
這裏是一個.NET 2溶液,將做同樣的事情,我以前發佈的LINQ解決方案。
DateTime today = DateTime.Today;
int daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);
List<DateTime> dates = new List<DateTime>();
bool foundFirst = false;
for (int n = 1; n <= daysInMonth; n++)
{
var date = new DateTime(today.Year, today.Month, n);
// Skip untill we find the first Monday of the month.
if (date.DayOfWeek != DayOfWeek.Monday && !foundFirst)
continue;
foundFirst = true;
// Add all days except Sundays.
if (date.DayOfWeek != DayOfWeek.Sunday)
dates.Add(date);
int remainingDays = daysInMonth - n;
// Verify that there are enough days left in this month to add all days upto the next Saturday.
if (date.DayOfWeek == DayOfWeek.Saturday && remainingDays < 7)
break;
}
DateTime[] dateArray = dates.ToArray();
最容易:
int month = DateTime.Now.Month;
int year = DateTime.Now.Year;
int days= DateTime.DaysInMonth(year, month);
int totalSaturdays = 0;
for(int i=1;i<=days;i++)
{
var day = new DateTime(year, month, i);
if(day.DayOfWeek==DayOfWeek.Saturday)
{
totalSaturdays++;
}
}
Console.WriteLine(("Total Saturdays ="+totalSaturdays.ToString()));
Console.ReadLine();
請格式化您的答案。在當前狀態下它不易讀 –
我使用2005 – Nathan
@Nathan我已經更新了我的回答還包括.NET 2.0解決方案。 –
非常感謝 – Nathan