Java Calendar Date and Time tips

Java Calendar Date and Time tips

Adding some utilities concerning Java date-related objects

Finding the number of months between two dates

import java.util.GregorianCalendar;
import java.util.Calendar;

public static int numberOfMonthsBetween(Date start, Date end){
    Calendar startCal = new GregorianCalendar();
    startCal.setTime(start);
    Calendar endCal = new GregorianCalendar();
    endCal.setTime(end);
    return (endCal.get(Calendar.YEAR) - startCal.get(Calendar.YEAR)) * 12
            + endCal.get(Calendar.MONTH) - startCal.get(Calendar.MONTH);
}

Date start = simpleDateFormat.parse("10-10-2021");
Date end = simpleDateFormat.parse("10-10-2022");
System.out.println("Number of months between "
                    + start + " and "
                    + end + " is " 
                    + numberOfMonthsBetween(start, end));

Output

Number of months between Sun Oct 10 00:00:00 IST 2021 and Mon Oct 10 00:00:00 IST 2022 is 12

Find if a date is a weekday

public static boolean isWeekDay(Date date){
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(date);
    if(Arrays.asList(Calendar.SATURDAY, Calendar.SUNDAY)
            .contains(gc.get(Calendar.DAY_OF_WEEK)))
        return false;
    else return true;
}
System.out.println(isWeekDay(simpleDateFormat.parse("09-10-2021")));

Output

true

Get the next business day

public static Date getNextBusinessDate(Date start) {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(start);
    switch (gc.get(Calendar.DAY_OF_WEEK)) {
        case Calendar.FRIDAY:
            gc.add(Calendar.DAY_OF_MONTH, 3);
            break;
        case Calendar.SATURDAY:
            gc.add(Calendar.DAY_OF_MONTH, 2);
            break;
        default:
            gc.add(Calendar.DAY_OF_MONTH, 1);
    }
    return gc.getTime();
}

System.out.println(getNextBusinessDate(simpleDateFormat.parse("09-10-2021")));

Output

Mon Sep 13 00:00:00 IST 2021