0

How do i set the textbox value to last day of last month(to end of previous month), using today's date.

for example:

if today is 23/03/2012 textbox value should be 29/02/2012 if come next month and date is 12/04/2012 then textbox value should be 31/03/2012 and so on

Thanks

Zaki
  • 5,540
  • 7
  • 54
  • 91
  • possible duplicate of [Get the previous month's first and last day dates in c#](http://stackoverflow.com/questions/591752/get-the-previous-months-first-and-last-day-dates-in-c-sharp) – itsmatt Mar 23 '12 at 12:47
  • Ha... got 4 duplicates just inside this question. Take your pick. – Chris Gessler Mar 23 '12 at 12:52

5 Answers5

2

Take the first day of the current month and subtract 1:

DateTime value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1);
mgnoonan
  • 7,060
  • 5
  • 24
  • 27
1
DateTime date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1);
textBox1.Text = date.ToShortDateString();
ionden
  • 12,536
  • 1
  • 45
  • 37
0

Use DateTime.DaysInMonth to accomplish this:

var daysInMonth = DateTime.DaysInMonth(dt.Year, dt.Month - 1);
var lastDayInMonth = new DateTime(dt.Year, dt.Month - 1, daysInMonth);
textBox1.Text = lastDayInMonth.ToString("dd/MM/yyyy");
David Morton
  • 16,338
  • 3
  • 63
  • 73
0

Get the first day of the month and subtract one day.

DateTime lastDayOfThePreviousMonth = dateSelected.AddDays(-dateSelected.Day);
daryal
  • 14,643
  • 4
  • 38
  • 54
0

In C#:

DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddDays(-1); 

Then call .ToString() and pass in whatever format you like.

Chris Gessler
  • 22,727
  • 7
  • 57
  • 83