Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#.Net Getting Last day of the Previous Month from current date

Tags:

c#

.net

A quick expression anyone please?

like image 606
Julius A Avatar asked Jul 16 '09 14:07

Julius A


3 Answers

var now = DateTime.Now;    
var firstDayCurrentMonth = new DateTime(now.Year, now.Month, 1);

var lastDayLastMonth = firstDayCurrentMonth.AddDays(-1);
like image 111
Seb Nilsson Avatar answered Nov 09 '22 21:11

Seb Nilsson


DateTime now = DateTime.Now;
DateTime lastDayOfLastMonth = now.Date.AddDays(-now.Day);
like image 26
LukeH Avatar answered Nov 09 '22 22:11

LukeH


Try the DateTime.DaysInMonth(int year, int month) method

Here's an example:

DateTime oneMonthAgo = DateTime.Now.AddMonths(-1);
int days = DateTime.DaysInMonth(oneMonthAgo.Year, oneMonthAgo.Month);
like image 4
Richard McGuire Avatar answered Nov 09 '22 22:11

Richard McGuire