计算前一周的开始和结束日期 [英] Calculate previous week's start and end date
本文介绍了计算前一周的开始和结束日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是计算前一周的开始和结束日期在C#中的最佳方式?即今天3月18日将导致3月9日(上周星期日)(上周星期一)3月15日。
What is the best way to calculate the previous week's start and end date in C#? I.e. today 18 March would result in 9 March (Monday last week) and 15 March (Sunday last week).
我已经看到了这与一周中的某天和一个switch语句完成的工作出的偏移,但不知道是否有一个更优雅的方式。
I have seen this done with DayOfWeek and a switch statement to work out an offset but was wondering whether there is a more elegant way.
推荐答案
您可以跳过while循环,并使用
You can skip the while loop and use
DateTime mondayOfLastWeek = date.AddDays( -(int)date.DayOfWeek - 6 );
这假设你使用星期一作为一周的第一天。
This assumes you're using Monday as the first day of the week.
这篇关于计算前一周的开始和结束日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文