Saturday, November 1, 2008

Get week start and week end in Java

I needed functions that can calculate the start and end of a week for any given day.
The functions will get 2 parameters: date and an index indicating the start of the week (for example: 2 means that the week starts at Monday).
Frankly, these functions are very simple, but still, when I can get something from Google in about 30 seconds, I always prefer to go in that way...

Well, I was pretty disappointed to find out that Google didn't give me anything that I can use. Usually I stop at the first results page, but for this one I also searched the second one. With no luck...

So, unhappily I had to write these 2 functions myself. I Hope it may save you the few minutes I wasted:

public static Date getWeekStart(Date date, int weekStart)
{
    Calendar calendar = getCalendar(date);
    while (calendar.get(Calendar.DAY_OF_WEEK) != weekStart)
    {
        calendar.add(Calendar.DATE, -1);
    }
    startOfDay(calendar);
    return calendar.getTime();
}

public static Date getWeekEnd(Date date, int weekStart)
{
    Calendar calendar = getCalendar(date);
    while (calendar.get(Calendar.DAY_OF_WEEK) != weekStart)
    {
        calendar.add(Calendar.DATE, 1);
    }

    calendar.add(Calendar.DATE, -1);
    endOfDay(calendar);
    return calendar.getTime();
}