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





As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles