Get last date of a month
Java Calendar #
In Java, we can use the Calendar class to get day_of_month, day_of_week etc. Last day of a month varies depending on the Month and on leap year we have extra day in February. So to figure out the last day of any given month in a year, we write some code which is apparently simple. Calendar object allows us to manipulate days, go forward or backward on the Calendar, add days, hours, minutes or seconds to any given time etc.
We will use these capabilities of Calendar class to get our last_of_month.
The idea here is to get the first day of next month and then reduce one day from it, which gives us the last day of the month relative to input date.
|
|
But, Java Calendar has a better way of doing this, by using getActualMaximum() method which is far more convenient.
|
|
Sample Util class code #
A sample calendar util class which gives you few convenient methods is given below.
|
|
References #
- https://stackoverflow.com/questions/13624442/getting-last-day-of-the-month-in-given-string-date/
- https://docs.oracle.com/javase/7/docs/api/java/util/Date.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
- https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html