简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM