Get the previous month's first and last day dates in c#

1,261

Solution 1

var today = DateTime.Today;
var month = new DateTime(today.Year, today.Month, 1);       
var first = month.AddMonths(-1);
var last = month.AddDays(-1);

In-line them if you really need one or two lines.

Solution 2

The way I've done this in the past is first get the first day of this month

dFirstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );

Then subtract a day to get end of last month

dLastDayOfLastMonth = dFirstDayOfThisMonth.AddDays (-1);

Then subtract a month to get first day of previous month

dFirstDayOfLastMonth = dFirstDayOfThisMonth.AddMonths(-1);

Solution 3

using Fluent DateTime https://github.com/FluentDateTime/FluentDateTime

        var lastMonth = 1.Months().Ago().Date;
        var firstDayOfMonth = lastMonth.FirstDayOfMonth();
        var lastDayOfMonth = lastMonth.LastDayOfMonth();

Solution 4

DateTime LastMonthLastDate = DateTime.Today.AddDays(0 - DateTime.Today.Day);
DateTime LastMonthFirstDate = LastMonthLastDate.AddDays(1 - LastMonthLastDate.Day);

Solution 5

I use this simple one-liner:

public static DateTime GetLastDayOfPreviousMonth(this DateTime date)
{
    return date.AddDays(-date.Day);
}

Be aware, that it retains the time.

Share:
1,261

Related videos on Youtube

Vlada Veljkovic
Author by

Vlada Veljkovic

Updated on April 16, 2020

Comments

  • Vlada Veljkovic
    Vlada Veljkovic about 4 years

    I have an issue with this type of error logging into the pm2 log file. There is no errors in browser, all API request statuses are 200. But, only on first use of application (when refresh page with browser button, or first time type URL) the error shows in log file. There is no error while using inner links for navigation.

    I'm using Angular Universal on node Express, and fulfill all requirements. Have CORS set up properly on server (nginx).

    There is an error:

    ERROR HttpErrorResponse {

    headers:

    HttpHeaders { normalizedNames: Map {}, lazyUpdate: null, headers: Map {} },
    

    status: 0,

    statusText: 'Unknown Error',

    url: 'https://www.example.com/api/get-menu-groups',

    ok: false,

    name: 'HttpErrorResponse',

    message:

    'Http failure response for https://www.example.com/api/get-menu-groups: 0 Unknown Error',
    

    error: ....}

    • David
      David over 4 years
      What happens if you try that API from the command line in the server, e.g. using wget ?
    • Vlada Veljkovic
      Vlada Veljkovic over 4 years
      It says: "cannot verify certificate....Unable to locally verify the issuer's authority". With --no-check-certificate, returns JSON with data. Note: https works in browsers.
    • David
      David over 4 years
      Try adding the following lines after the imports in your server.ts file and see if it works: process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; `
    • Vlada Veljkovic
      Vlada Veljkovic over 4 years
      No, same thing. Actually, I solved problem with certificate, and now, when I try API from command line, it returns proper json. But, when I try from command line on server (using SSH console) I get 'unable to resolve host address (domain)'. Very strange
    • Vlada Veljkovic
      Vlada Veljkovic over 4 years
      For the future, who face the same issue, problem was in bad configuration of some basic Angular Universal files. Follow the instructions from this page and everything will be OK. github.com/angular/universal/blob/master/docs/…
    • Juano7894
      Juano7894 almost 2 years
      I have the same issue on my project. But the link you provided doesnt show much, at least that is not my problem. Do you remember what configuration was the issue?
  • andleer
    andleer about 15 years
    DateTime.Today.Days -> 'System.DateTime' does not contain a definition for 'Days'...
  • Joe
    Joe about 15 years
    +1, but to be pedantic, you're better evaluating DateTime.Today once and storing in a local variable. If your code starts executing a nanosecond before midnight, two consecutive calls to DateTime.Today could return different values.
  • Amy B
    Amy B about 15 years
    What if DateTime.Now yields 2009-01-31 on the first call and 2009-02-01 on the second call?
  • Jonathan Olson
    Jonathan Olson about 15 years
    Yes, thanks, all of you correct, even the pedantic one Fixed the error.
  • Leandro López
    Leandro López about 15 years
    IIRC DateTime.Today is a quite expensive call, so you better store the value in a variable first. Good answer anyway :)
  • mohsin shabir
    mohsin shabir about 15 years
    well let the compiler be less pedantic to you :)
  • Terry_Brown
    Terry_Brown about 12 years
    upvoted as was comparing return date.AddDays(-(date.Day-1)) versus return new DateTime(date.Year, date.Month, 1); and the performance of the first over 2000 iterations is better (923ms newing up versus 809ms returning the same object)
  • Matthew Lock
    Matthew Lock almost 12 years
    @andleer here's a nice library which works like you mentioned fluentdatetime.codeplex.com
  • Guillermo Gutiérrez
    Guillermo Gutiérrez about 11 years
    @MatthewLock, the link seems to be broken.
  • Matthew Lock
    Matthew Lock about 11 years
  • SixOThree
    SixOThree over 9 years
    I would just like to point out that if entries are stored using a a full datetime this query may fail to retrieve any that start after 12:00 AM on the last day of the month. You could solve this by changing the last line to read var last = month.AddTicks(-1);
  • Joe Ballard
    Joe Ballard over 7 years
    Just what I wanted, concise expression I could use inside a ternary. Thanks!
  • Vlada Veljkovic
    Vlada Veljkovic over 4 years
    How can it be possible when there are values, rendered on page?