0

This is how I currentyl get the first date of last month:

Frmdate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
Frmdate.AddMonths(-1).ToString("dd/MM/yyyy");

The result is 01/01/2015.

When I am in february:

ToDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
ToDate.AddMonths(-1).ToString("dd/MM/yyyy");

The result is 28/01/2015, but I need 31/01/2015.

I need a way to solve this only for the month of february.

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
Mohammad Asif
  • 13
  • 1
  • 3

2 Answers2

5

Instead of AddMonths use AddDays function:

ToDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
ToDate.AddDays(-1).ToString("dd/MM/yyyy");

Here is a working fiddle.

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
Jenish Rabadiya
  • 6,708
  • 6
  • 33
  • 62
2

Last month first day:

 DateTime firstDayLastMonth = DateTime.Now.AddDays(1 - DateTime.Now.Day).AddMonths(-1);

last month last day:

DateTime lastDayLastMonth = new DateTime(firstDayLastMonth.Year, firstDayLastMonth.Month, DateTime.DaysInMonth(firstDayLastMonth.Year, firstDayLastMonth.Month));
Irfan TahirKheli
  • 3,652
  • 1
  • 22
  • 36