tags:

views:

308

answers:

5

If i have this date 03/08/1980 and I need to find the last day of the month (08)

(the last day of 08 - is 31)

How can I do it ? (in C#)

+12  A: 
  DateTime firstOfNextMonth = new DateTime(date.Year, date.Month, 1).AddMonths(1);
  DateTime lastOfThisMonth = firstOfNextMonth.AddDays(-1);
Henk Holterman
You beat me to it, and with a clearer answer. +1 for you.
Beska
+3  A: 

How about substracting a day from the 1st of next month ?

DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month+1,1).AddDays(-1);

Edit: also, in case you need it to work for December too:

DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month,1).AddMonths(1).AddDays(-1);
Radu094
Make sure you test that with a myDate in December.
Henk Holterman
hmm.. you mean you need it to work for December months too ? :-)
Radu094
I don't know, the question only mentions August.
Henk Holterman
+28  A: 
var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);
Mark
this one is pure beauty!
Andreas Niedermair
I assumed 'date of last day in month', but otherwise your answer is better.
Henk Holterman
@Henk Actually I pulled this from a place in our source that creates the `DateTime` from the `lastDayOfMonth`. Honestly either way works perfectly well. It's a pedantic argument which way is better. I've done it both ways and both yield the same answer.
Mark
Mark, no. Your result is an `int`, mine a `DateTime`. Its about who of us read (guessed) the specs the best.
Henk Holterman
How come you get all the creds, my answer was first :(
Oskar Kjellin
@Kurresmack It looks like I beat you by a hair. Mine = 14:43:02 Yours = 14:43:36 If it's any help, I up voted you too.
Mark
Oh dang. Seems about true. Hmm, I mixed up :S Uped you too :P
Oskar Kjellin
A: 

I don't know C# but, if it turns out there's not a convenient API way to get it, one of the ways you can do so is by following the logic:

today -> +1 month -> set day of month to 1 -> -1 day

Of course, that assumes you have date math of that type.

RHSeeger
+13  A: 

The last day of the month you get like this, which returns 31:

DateTime.DaysInMonth(1980, 08);
Oskar Kjellin