如何在c#中获取上周开始日期和上个月的开始日期?

use*_*802 0 c#

我想根据上周和上个月在c#中检索记录.对于上周我想要从星期日到星期六的记录.对于上个月我想要获得上个月的开始日期来获取所有记录,直到该月末.

我不应该在上周获取最近六天的记录,而是想从当前周(星期日)开始日期找到最后一个星期日.

我找到了找到上个月第一天和最后一天的解决方案---->

 var first = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(-1);
                    var last = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddDays(-1);
Run Code Online (Sandbox Code Playgroud)

上周发现----->

DateTime _currDateTime = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Unspecified);
                    DateTime _currentDate;
                    DateTime _lastWeekStartDate;
                    _currentDate = _currDateTime.StartOfWeek(DayOfWeek.Sunday);
                    _lastWeekStartDate = _currentDate.AddDays(-1);
                    tempfromdate = _lastWeekStartDate.StartOfWeek(DayOfWeek.Sunday);
                    temptodate = tempfromdate.EndOfWeek(DayOfWeek.Saturday);
Run Code Online (Sandbox Code Playgroud)

Øyv*_*hen 5

这至少是一种做法

DateTime lastWeekFirstDay = DateTime.Now.AddDays( - 6 - (int)DateTime.Now.DayOfWeek);
DateTime lastMonthFirstDay = DateTime.Now.AddMonths( -1 ).AddDays( 1 - DateTime.Now.Day);
Run Code Online (Sandbox Code Playgroud)

如果星期日是您文化中一周的第一天,请在第一行代码中将6替换为7.6假设星期一是一周的第一天.

编辑

添加了月变体的变体,可能更具可读性:

DateTime lastMonthFirstDay = new DateTime( DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);
Run Code Online (Sandbox Code Playgroud)