Tuesday, August 3, 2010

Get Next Business Day Date Object in Java

To get a java.util.Date object representing the next business day, we
can use the java.util.Calendar class. First, create a Calendar object
and set it's time with a Data object. Next, check what day of the week
it is and increment it accordingly to the next weekday. Finally,
create a new Date object with the Calendar's getTime() method.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

// Java 1.4+ Compatible
//
// The following example code demonstrates how to determine
// the next business day given a Date object.

public class GetNextBusinessDay {

    public static void main(String[] args) {

        Date today = new Date();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(today);

        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

        if (dayOfWeek == Calendar.FRIDAY) {
            calendar.add(Calendar.DATE, 3);
        } else if (dayOfWeek == Calendar.SATURDAY) {
            calendar.add(Calendar.DATE, 2);
        } else {
            calendar.add(Calendar.DATE, 1);
        }

        Date nextBusinessDay = calendar.getTime();

        DateFormat sdf = new SimpleDateFormat("EEEE");
        System.out.println("Today            : " + sdf.format(today));
        System.out.println("Next business day: " + sdf.format(nextBusinessDay));

    }

}

Here is the output of the example code:
Today            : Tuesday
Next business day: Wednesday

No comments: