Tuesday, August 3, 2010

Get Previous Business Day Date Object in Java

To get a java.util.Date object representing the previous 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 decrement it accordingly to the previous weekday.
Finally, create a new Date object with the Calendar's getTime()
method.


Get Previous Business Day Date Object in Java - Example Code

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 GetPreviousBusinessDay {

    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.MONDAY) {
            calendar.add(Calendar.DATE, -3);
        } else if (dayOfWeek == Calendar.SUNDAY) {
            calendar.add(Calendar.DATE, -2);
        } else {
            calendar.add(Calendar.DATE, -1);
        }

        Date previousBusinessDay = calendar.getTime();

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

}

Here is the output of the example code:
Today                : Tuesday
Previous business day: Monday

2 comments:

Anonymous said...

what about national holidays ?

Tim Molter said...

The business days - mon thru Fri, are always business days somewhere. To account for a nation's holidays, you'd have to create a custom calendar and account for the holidays, since the JRE doesn't have this information.