Ilkar Ilkar -4 years ago 192
Java Question

java calendar - get last 5 days of week (without weekend)

I'm working with some issue.

I need to get some data from database

1) get 5 records from 5 last days (one record per one day), but the days must be the days of a week (now a weekend)

2) get 20 records from the month (current or past, one record per one day)

I'm fighting with Java Calendar, but still i have no idea, how to get the dates.

Could anybody help me?

Answer Source

Should work:

private Calendar workingDaysBack(final Calendar from, final int count) {
    for (int daysBack = 0; daysBack < count; ++daysBack) {
        do {
            from.add(Calendar.DAY_OF_YEAR, -1);
        } while(isWeekend(from));
    return from;

private boolean isWeekend(Calendar cal) {
    return cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ||
           cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download