得到当前月份的星期一到星期六
本文关键字:星期一 星期六 | 更新日期: 2023-09-27 18:12:43
在一个月内,我想知道当前月份的星期一到星期六,例如:在2011年10月,有
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();
这将做同样的事情,除了删除任何不在当前月份的Monday -> Saturday范围。(一周在前一个月开始,或在下一个月结束)。
编辑:这是一个。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();
高效解决方案;
var x = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
int i = 1;
while (i <= x)
{
if (new DateTime(DateTime.Now.Year, DateTime.Now.Month, i).DayOfWeek == DayOfWeek.Saturday)
{
Console.WriteLine(new DateTime(DateTime.Now.Year, DateTime.Now.Month, i));
i += 6;
}
i++;
}