Get the previous month's first and last day dates in c#
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.
Related videos on Youtube
Vlada Veljkovic
Updated on April 16, 2020Comments
-
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 over 4 yearsWhat happens if you try that API from the command line in the server, e.g. using wget ?
-
Vlada Veljkovic over 4 yearsIt 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 over 4 yearsTry 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 over 4 yearsNo, 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 over 4 yearsFor 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 almost 2 yearsI 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 about 15 yearsDateTime.Today.Days -> 'System.DateTime' does not contain a definition for 'Days'...
-
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 about 15 yearsWhat if DateTime.Now yields 2009-01-31 on the first call and 2009-02-01 on the second call?
-
Jonathan Olson about 15 yearsYes, thanks, all of you correct, even the pedantic one Fixed the error.
-
Leandro López about 15 yearsIIRC DateTime.Today is a quite expensive call, so you better store the value in a variable first. Good answer anyway :)
-
mohsin shabir about 15 yearswell let the compiler be less pedantic to you :)
-
Terry_Brown about 12 yearsupvoted as was comparing
return date.AddDays(-(date.Day-1))
versusreturn 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 almost 12 years@andleer here's a nice library which works like you mentioned fluentdatetime.codeplex.com
-
Guillermo Gutiérrez about 11 years@MatthewLock, the link seems to be broken.
-
Matthew Lock about 11 years@guillegr123 now at github github.com/FluentDateTime/FluentDateTime and Nuget nuget.org/packages/FluentDateTime
-
SixOThree over 9 yearsI 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 over 7 yearsJust what I wanted, concise expression I could use inside a ternary. Thanks!
-
Vlada Veljkovic over 4 yearsHow can it be possible when there are values, rendered on page?