简体   繁体   中英

Set a date variable that equals to previous month's full month

This is probably a silly question. Is it possible to set a variable value that I could use to get data from the previous month's days? For example, if it's the 24th of September, I want everything from the 1st of August until the 31st of August. So the current date shouldn't matter. I'm using it in a Stock Take report. I use this currently:

var firstDayofPreviousMonth = DateTime.Today.AddMonths(-1);

The report runs automatically on the 1st of each month. So I figured, just pull from 1 month back, but my boss suddenly changed her mind and wants to pull the report everyday.

Does this make sense? Pop a comment if you need more information.

Here are the methods i use for this:

public static DateTime GetStartOfLastMonth(DateTime dt)
        {
            var date = dt.AddMonths(-1);
            return new DateTime(date.Year, date.Month, 1, 0, 0, 0, DateTimeKind.Local);
        }

        public static DateTime GetEndOfLastMonth(DateTime dt)
        {
            var date = dt.AddMonths(-1);
            var daysInLastMonth = DateTime.DaysInMonth(date.Year, date.Month);

            return new DateTime(date.Year, date.Month, daysInLastMonth, 0, 0, 0, DateTimeKind.Local);
        }

Note: depending on your case, you may want to change GetEndOfLastMonth to be 23,59,59 . Since i operate in dates, this is irrelevant for the library this code is in.

DateTime refDate = DateTime.Now.AddMonths(-1);
DateTime firstDayPreviousMonth = new DateTime(refDate.Year, refDate.Month, 1);
DateTime lastDayPreviousMonth = new DateTime(refDate.Year, refDate.Month, DateTime.DaysInMonth(refDate.Year,refDate.Month));

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