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,348
  • 7
  • 51
  • 90
  • 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
  • 6,962
  • 5
  • 23
  • 27
1
DateTime date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1);
textBox1.Text = date.ToShortDateString();
ionden
  • 12,216
  • 1
  • 43
  • 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
  • 15,960
  • 2
  • 61
  • 72
0

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

DateTime lastDayOfThePreviousMonth = dateSelected.AddDays(-dateSelected.Day);
daryal
  • 14,403
  • 4
  • 36
  • 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,017
  • 6
  • 53
  • 80