开发者

How to get last week begin date and last month begin date in c#?

开发者 https://www.devze.com 2023-02-16 11:21 出处:网络
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

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.

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. 6 assumes Monday is the first day of the week.

EDIT

Added a variant of the month variant that is probably a bit more readable:

DateTime lastMonthFirstDay = new DateTime( DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);
0

精彩评论

暂无评论...
验证码 换一张
取 消