Thursday, December 17, 2009

Java: calculate last Saturday

Java method that returns the date of last Saturday with time set to (00:00:00):

public class DateHelper
{

  public static Date getLastSatuerday(Date date)
    {
Calendar calendar = Calendar.getInstance();
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
Date lastSat = DateHelper.incrementDays(date, (-weekday));

Calendar cal = new GregorianCalendar();
cal.setTime(lastSat);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
    }

//increment hours of day

    public static Date incrementHours(Date date, int hours)
    {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, hours);
return calendar.getTime();
    }

}
JUnit test for above method: 

  public void test_getLastSatuerday()
    {
Date date = DateHelper.buildToday();
date = DateHelper.incrementHours(date, 2);
Date weekday = DateHelper.getLastSatuerday(date);
log.warn("Today is: " + date + " , last sat is: " + weekday);
    }


Output:
WARN 2009-12-17 09:05:42.306 com.xxx.xxx.server.common.DateHelperTest.test_getLastSatuerday()
Today is: Thu Dec 17 02:00:00 CST 2009 , last sat is: Sat Dec 12 00:00:00 CST 2009