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
- http://stackoverflow.com/questions/13624442/getting-last-day-of-the-month-in-given-string-date/
- http://docs.oracle.com/javase/7/docs/api/java/util/Date.html
- http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
- http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
- http://docs.oracle.com/javase/7/docs/api/java/util/Locale.html
Author: Deepu Mohan Puthrote
Link: https://deepumohan.com/tech/get-last-date-of-month/
This work by Deepu Mohan Puthrote is licensed under a Creative Commons Attribution 4.0 International License