|
-
Feb 10th, 2011, 11:37 AM
#1
Thread Starter
Addicted Member
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
-
Feb 10th, 2011, 12:39 PM
#2
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
-
Feb 10th, 2011, 12:41 PM
#3
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
-
Feb 10th, 2011, 01:19 PM
#4
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..
* Rate It  If you Like it
__________________________________________________________________________________________
" Programming is like sex: one mistake and you’re providing support for a lifetime."
Get last SQL insert ID 
-
Feb 10th, 2011, 01:35 PM
#5
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
-
Feb 10th, 2011, 02:39 PM
#6
Re: How to last day of last month??
* Rate It  If you Like it
__________________________________________________________________________________________
" Programming is like sex: one mistake and you’re providing support for a lifetime."
Get last SQL insert ID 
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|