I need the start date and the end date of the current month in Java. When the JSP page is loaded with the current month it should automatically calculate the start and end date of that month. It should be irrespective of the year and month. That is some month has 31 days or 30 days or 28 days. This should satisfy for a leap year too. Can you help me out with that?
For example if I select month May in a list box I need starting date that is 1 and end date that is 31.
To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates. Copied! const now = new Date(); const firstDay = new Date(now.
Use the getActualMaximum() method to get the last day of the month. int res = cal. getActualMaximum(Calendar. DATE);
Use the new Date() constructor to get a date object. Call the getMonth() method on the object and add 1 to the result. The getMonth method returns a zero-based month index so adding 1 returns the current month.
There you go:
public Pair<Date, Date> getDateRange() { Date begining, end; { Calendar calendar = getCalendarForNow(); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); setTimeToBeginningOfDay(calendar); begining = calendar.getTime(); } { Calendar calendar = getCalendarForNow(); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); setTimeToEndofDay(calendar); end = calendar.getTime(); } return Pair.of(begining, end); } private static Calendar getCalendarForNow() { Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(new Date()); return calendar; } private static void setTimeToBeginningOfDay(Calendar calendar) { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); } private static void setTimeToEndofDay(Calendar calendar) { calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); calendar.set(Calendar.MILLISECOND, 999); }
PS: Pair
class is simply a pair of two values.
If you have the option, you'd better avoid the horrid Java Date API, and use instead Jodatime. Here is an example:
LocalDate monthBegin = new LocalDate().withDayOfMonth(1); LocalDate monthEnd = new LocalDate().plusMonths(1).withDayOfMonth(1).minusDays(1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With