答案 0 :(得分:3)
DateTime.DayOfWeek
是一个枚举,以星期日为0并向前开始。如果您参加今天的星期几,它也会告诉我们星期天的情况。因此,假设在星期日的星期开始,那么回去那么多天会给你本周日的星期日。你可以在一周的七天里继续前进。
var today = DateTime.Now;
var thisSunday = today.AddDays(-(int)today.DayOfWeek);
for (int i=0; i<7; i++)
Console.WriteLine(thisSunday.AddDays(i).ToString());
如果一周从星期一开始,请使用
var thisMonday = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
答案 1 :(得分:0)
您可以使用扩展方法设置以(credit goes to @Compile This)
开头的那一周public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime datetime, DayOfWeek startOfWeek)
{
int difference = datetime.DayOfWeek - startOfWeek;
if (difference >= 0)
return datetime.AddDays(-1 * difference).Date;
difference += 7;
return datetime.AddDays(-1 * difference).Date;
}
}
然后你可以使用@Sami_Kuhmonen提到的相同循环来获取一周的日期:
DateTime d = DateTime.Now.StartOfWeek(DayOfWeek.Saturday);
for (int i = 0; i < 7; i++)
Console.WriteLine(d.AddDays(i));