0

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.

2 Answers2

1

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.

zaitsman
  • 8,984
  • 6
  • 47
  • 79
  • @JudithJoubert just pass `22` for the hour part? – zaitsman Nov 20 '17 at 12:07
  • Thanks I got it. Thank you. Appreciate your help. `2017-10-31 11:59:59 PM` `2017-10-01 01:05:00 AM` –  Nov 20 '17 at 12:09
  • 1
    I only have like 12 rep (I just started this) so I will upvote your answer once I hit the last 3. Thanks alot hey –  Nov 20 '17 at 12:11
0
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));