【问题标题】:How can I find Saturdays and Sundays in A given month?如何找到给定月份的周六和周日?
【发布时间】:2012-03-28 14:13:58
【问题描述】:

我想找到给定月份的所有周六和周日。我该怎么做?

【问题讨论】:

    标签: java android date calendar


    【解决方案1】:

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

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

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

    使用现代日期时间 API java.time 的解决方案:

    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 了解有关现代日期时间 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

    【讨论】:

      【解决方案2】:

      最简单的方法是遍历一个月中的所有日子,并检查每一天的星期几。例如:

      // 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,那会让您的生活更轻松...

      【讨论】:

        【解决方案3】:

        试试这个:

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

        【讨论】:

          【解决方案4】:

          根据上一个答案,我有一个小的修改 当您找到第一个星期六和星期日时,您可以简单地添加 7 天,直到更改月份。

          【讨论】:

            【解决方案5】:

            请通过这个方法,我遇到了很多最后我创建了自己的。

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

            它会给你准确的结果。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-01-20
              相关资源
              最近更新 更多