我怎样才能找到一个月内的星期六和星期日?

时间:2012-03-28 14:13:58

标签: java android date calendar

我希望找到一个月内的所有星期六和星期日。我怎么能这样做?

5 个答案:

答案 0 :(得分:9)

最简单的方式是迭代月中的所有日子,并检查每个日期的星期几。例如:

// 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;
}

绝对确定有更有效的方法可以做到这一点 - 但这就是我的开始,并在我发现它太慢时进行优化。

请注意,如果您能够使用Joda Time,这会让您的生活更轻松......

答案 1 :(得分:1)

试试这个:

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);
    }
}

答案 2 :(得分:1)

根据之前的回答,我做了一个小修改 当你找到第一个星期六和星期日时,你可以简单地添加7天,直到月份改变。

答案 3 :(得分:1)

java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到 modern Date-Time API*

此外,下面引用的是 Home Page of Joda-Time 处的通知:

<块引用>

请注意,从 Java SE 8 开始,要求用户迁移到 java.time (JSR-310) - JDK 的核心部分,取代了该项目。

使用 java.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());
    }
}

输出:

[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

Stream解决方案:

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

Trail: Date Time 了解有关现代 Date-Time API 的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 & 7. 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

答案 4 :(得分:0)

请通过这种方法,我最终遇到了很多,我创造了自己的方法。

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;
}

它会给你准确的结果。