C# DayOfWeek获取上周,本周,下周(周一到周日)

1.DayOfWeek是从周日到周六的顺序,即枚举值是从0到6;周日:0 周一:1......

2.怎么根据当前日期算出上周:

var ss = DateTime.Now.AddDays(0 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7).ToString("yyyy-MM-dd");//上周日
var ssss= DateTime.Now.AddDays(6 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7).ToString("yyyy-MM-dd");//上周六

所以要想知道上周一到上周日的数据,即每个都加+1天即可

var ssss = DateTime.Now.AddDays(0 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7+1).ToString("yyyy-MM-dd");//上周一
var sssss= DateTime.Now.AddDays(6 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7+1).ToString("yyyy-MM-dd");//上周日

网上还有另外一种写法取上周的数据:

var date = DateTime.Now;
var m = (date.DayOfWeek == DayOfWeek.Sunday ? (DayOfWeek)7 : date.DayOfWeek) - DayOfWeek.Monday;
var s = (date.DayOfWeek == DayOfWeek.Sunday ? (DayOfWeek)7 : date.DayOfWeek) - (DayOfWeek)7;
var Mon = date.AddDays((-7 - m)).ToString("yyyy-MM-dd");
var Sun = date.AddDays((-7 - s)).ToString("yyyy-MM-dd");
Console.WriteLine(Mon);
Console.WriteLine(Sun);

3.本周数据

DateTime.Now.AddDays(0 - Convert.ToInt16(DateTime.Now.DayOfWeek)+1)

DateTime.Now.AddDays(6 - Convert.ToInt16(DateTime.Now.DayOfWeek)+1)

4.下周数据

DateTime.Now.AddDays(0 - Convert.ToInt16(DateTime.Now.DayOfWeek) + 7+1)

DateTime.Now.AddDays(6 - Convert.ToInt16(DateTime.Now.DayOfWeek) + 7+1)

 

posted @ 2021-03-10 09:38  雨中超越  阅读(4465)  评论(0编辑  收藏  举报