How to last day of last month??
I am trying to get last day of last month (say today is 02/11/2011 and I need 01/31/2011).
How can I do that in C#
The following code will get last day of any month that user types into TextBoxPeriod.Text. Based on the system date, I need to get last day of last month.
DateTime aSelectedDate = Convert.ToDateTime(TextBoxPeriod.Text);
DateTime datlastDayOfThisMonth = new DateTime(aSelectedDate.Year, aSelectedDate.Month, 1).AddMonths(1).AddDays(-1);
lastDayOfThisMonth = Convert.ToString(datlastDayOfThisMonth);
lastDayOfThisMonth = lastDayOfThisMonth.Substring(0, 10);
Thanks
nath
Re: How to last day of last month??
Arrrrgh.... you made me think about it...
Did it all in one line. This will get the last day of the month with respect to the current date.
Code:
DateTime endOfLastMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1);
It is deceptively simple... get the first of the current month... then subtract one day.
-tg
Re: How to last day of last month??
BTW: these lines are unnecessary:
Code:
lastDayOfThisMonth = Convert.ToString(datlastDayOfThisMonth);
lastDayOfThisMonth = lastDayOfThisMonth.Substring(0, 10);
If you want jsut the day part... use this instead:
enfoLastMonth.Day;
If you need it as a string:
endOfLastMonth.Day.ToString();
it's that simple.
-tg
Re: How to last day of last month??
He posted them thread in the ASP.NET forums as well.. (which I had the answer as you tech :))
Nath I don't think it's allowed to post the same question in multiple forums..
Re: How to last day of last month??
motil - if you find a link to the other, report it as a dupe thread and give a link to both... the admins can merge the threadfs and put it in the right place (C#).
-tg
Re: How to last day of last month??