9

I want find all Saturdays and Sundays in A given month. How can I do so?

Bart
  • 19,692
  • 7
  • 68
  • 77
Venkat
  • 343
  • 1
  • 7
  • 17

5 Answers5

11

The simplest way is to just iterate over all the days in the month, and check the day of week for each of them. For example:

// This takes a 1-based month, e.g. January=1. If you want to use a 0-based
// month, remove the "- 1" later on.
public int countWeekendDays(int year, int month) {
    Calendar calendar = Calendar.getInstance();
    // Note that month is 0-based in calendar, bizarrely.
    calendar.set(year, month - 1, 1);
    int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

    int count = 0;
    for (int day = 1; day <= daysInMonth; day++) {
        calendar.set(year, month - 1, day);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == Calendar.SUNDAY || dayOfweek == Calendar.SATURDAY) {
            count++;
            // Or do whatever you need to with the result.
        }
    }
    return count;
}

I'm absolutely sure there are far more efficient ways of doing this - but that's what I'd start with, and optimize when I'd found it's too slow.

Note that if you're able to use Joda Time that would make your life a lot easier...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Try this:

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Sundays {
    public static void main(String[] args) {
        int year = 2012;

        // put the month you want
        int month = Calendar.JANUARY;

        Calendar cal = new GregorianCalendar(year, month, 1);
        do {
            int day = cal.get(Calendar.DAY_OF_WEEK);
            if (day == Calendar.SATURDAY || day == Calendar.SUNDAY) {
                System.out.println(cal.get(Calendar.DAY_OF_MONTH));
            }
            cal.add(Calendar.DAY_OF_YEAR, 1);
        }  while (cal.get(Calendar.MONTH) == month);
    }
}
Bart
  • 19,692
  • 7
  • 68
  • 77
Marcos
  • 4,643
  • 7
  • 33
  • 60
1

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Also, quoted below is a notice at the Home Page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getWeekends(2));// All weekends of Feb in the current year
        System.out.println(getWeekends(2020, 2));// All weekends of Feb 2020
    }

    /*
     * All weekends (Sat & Sun) of the given month in the current year
     */
    static List<LocalDate> getWeekends(int month) {
        LocalDate firstDateOfTheMonth = LocalDate.now().withMonth(month).with(TemporalAdjusters.firstDayOfMonth());
        
        return firstDateOfTheMonth
                .datesUntil(firstDateOfTheMonth.plusMonths(1))
                .filter(date -> date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
                .collect(Collectors.toList());
    }

    /*
     * All weekends (Sat & Sun) of the given year and the month
     */
    static List<LocalDate> getWeekends(int year, int month) {
        LocalDate firstDateOfTheMonth = YearMonth.of(year, month).atDay(1);
        
        return firstDateOfTheMonth
                .datesUntil(firstDateOfTheMonth.plusMonths(1))
                .filter(date -> date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
                .collect(Collectors.toList());
    }
}

Output:

[2021-02-06, 2021-02-07, 2021-02-13, 2021-02-14, 2021-02-20, 2021-02-21, 2021-02-27, 2021-02-28]
[2020-02-01, 2020-02-02, 2020-02-08, 2020-02-09, 2020-02-15, 2020-02-16, 2020-02-22, 2020-02-23, 2020-02-29]

ONLINE DEMO

Non-Stream solution:

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getWeekends(2));// All weekends of Feb in the current year
        System.out.println(getWeekends(2020, 2));// All weekends of Feb 2020
    }

    /*
     * All weekends (Sat & Sun) of the given month in the current year
     */
    static List<LocalDate> getWeekends(int month) {
        LocalDate firstDateOfTheMonth = LocalDate.now().withMonth(month).with(TemporalAdjusters.firstDayOfMonth());
        List<LocalDate> list = new ArrayList<>();

        for (LocalDate date = firstDateOfTheMonth; !date
                .isAfter(firstDateOfTheMonth.with(TemporalAdjusters.lastDayOfMonth())); date = date.plusDays(1))
            if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
                list.add(date);

        return list;
    }

    /*
     * All weekends (Sat & Sun) of the given year and the month
     */
    static List<LocalDate> getWeekends(int year, int month) {
        LocalDate firstDateOfTheMonth = YearMonth.of(year, month).atDay(1);
        List<LocalDate> list = new ArrayList<>();

        for (LocalDate date = firstDateOfTheMonth; !date
                .isAfter(firstDateOfTheMonth.with(TemporalAdjusters.lastDayOfMonth())); date = date.plusDays(1))
            if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
                list.add(date);

        return list;
    }
}

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

Base on the previous answer, I have a small modification When u find the first Saturday and Sunday, you can simply add 7 days to it until the month is changed.

Bear
  • 5,138
  • 5
  • 50
  • 80
0

Please go through this method, I faced a lot finally I created my own.

public static int getDayDiff(String dateFrom, String dateTo){ // DD/MM/YYYY
    Timestamp tDtF = getTimestampDDmmYYYY(dateFrom);//returning timestamp from / DD/MM/YYYY
    Timestamp tDtT = getTimestampDDmmYYYY(dateTo);
    Calendar dtF = new GregorianCalendar();
    Calendar dtT = new GregorianCalendar();
    dtF.setTimeInMillis(tDtF.getTime());
    dtT.setTimeInMillis(tDtT.getTime());
    int count = 0;
    while(dtF.before(dtT)){
        count++;
        dtF.add(Calendar.DAY_OF_YEAR, 1);
    }
    return count;
}

public static int countDateSatOrSun(String dateFrom, String dateTo){//DD/MM/YYYY
    Timestamp tDtF = getTimestampDDmmYYYY(dateFrom);//returning timestamp from / DD/MM/YYYY
    Timestamp tDtT = getTimestampDDmmYYYY(dateTo);
    Calendar dtF = new GregorianCalendar();
    Calendar dtT = new GregorianCalendar();
    dtF.setTimeInMillis(tDtF.getTime());
    dtT.setTimeInMillis(tDtT.getTime());
    int count = 0;
    while(dtF.before(dtT)){
        if((dtF.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY| dtF.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY))
                count++;
        dtF.add(Calendar.DAY_OF_YEAR, 1);
    }
    return count;
}

It will give you exact result.