Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
how to find out month end from a specific date

example

1/1/2010 month end day = 31/1/2010

15/5/2013 month end day = 31/5/2013



is any method ???
Posted
Comments
Philippe Mori 15-May-13 8:52am    
First of all, it should be easy to figure out solution 4 (find first day of next month and substract 1) without doing any search. Otherwise, reading the official documentation or using Google would be the right thing to do. There are so much question on DateTime on the web that almost everything someone can think of is already explained multiple times.

The last day of the month you get like this, which returns 31:
C#
DateTime.DaysInMonth(2010, 01);

You can also get it by using:
C#
var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);
 
Share this answer
 
very simple approach
just get the date for first day of next month (which is always 1st)
and deduct 1 day from datetime object.

this way you need not to worry for leap years also, this will always work.


hope this helps you.
 
Share this answer
 
If the date is given as string, it must be converted to a numeric format which allows getting the month and year number. Then you can use these formulas:
C++
bool IsLeapYear(int nYear)
{ 
    return (nYear % 4) == 0 && ((nYear % 100) != 0 || (nYear % 400) == 0); 
}

// Get number of days per month. NOTE: nMonth is 1 based!
int GetDaysOfMonth(int nYear, int nMonth)
{ 
    return 31 - ((nMonth == 2) ? (3 - IsLeapYear(nYear)) : (((nMonth - 1) % 7 ) % 2)); 
}
 
Share this answer
 
Comments
Philippe Mori 15-May-13 8:48am    
Very bad idea to write your own code when you can uses existing functions... The best way would be to use DaysInMonth as suggested in solution 1. Assuming that you don't know such function existing, then solution 4 would be the right approach (find first day on next month and substract 1 day).
Jochen Arndt 15-May-13 9:04am    
The question is tagged C++/MFC but DaysInMonth() is a .NET/CLI function.

Solution 4 is correct but requires incrementing the month, incrementing the year upon overflow, and finally subtracting one day by creating another date object. While this overhead can be accepted in most circumstances, it may be not always acceptable.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900