[英]How to get last week begin date and last month begin date in c#?
i want to retrieve records based on last week and last month in c#.For last week i want records from sunday to saturday.For last month i want to get last month begin date to fetch all the records till end of that month. 我想检索基于上周和上个月在C#中的记录。对于上周,我想要从星期日到星期六的记录。对于上个月,我想获取上个月的开始日期以获取所有记录,直到该月末。
i should not fetch last six days records for last week instead i want to find last sunday date from current week(sunday) begin date. 我不应该获取上周的过去六天记录,而是我想从当前周(星期日)开始日期中找到最后一个星期日日期。
i found solution for finding last month first and last day----> 我找到了找到上个月第一天和最后一天的解决方案---->
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);
finding last week-----> 找到上周----->
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);
This is at least a way of doing it 这至少是一种方法
DateTime lastWeekFirstDay = DateTime.Now.AddDays( - 6 - (int)DateTime.Now.DayOfWeek);
DateTime lastMonthFirstDay = DateTime.Now.AddMonths( -1 ).AddDays( 1 - DateTime.Now.Day);
Replace the 6 with 7 in the first line of code if Sunday is the first day of the week in your culture. 如果星期日是您所在地区的一周的第一天,请在第一行代码中将7替换为6。 6 assumes Monday is the first day of the week.
6假设星期一是一周的第一天。
EDIT 编辑
Added a variant of the month variant that is probably a bit more readable: 添加了month变体的变体,该变体可能更具可读性:
DateTime lastMonthFirstDay = new DateTime( DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.