有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何使用java获取一个月的第一个星期日

我要争取一个月的第一个星期天。 我达到的目的是得到一年中所有的星期天

import static java.time.temporal.TemporalAdjusters.firstInMonth;

    public static void FindAllSundaysOfTheYear () {
        // Create a LocalDate object that represent the first day of the year.
        int year = 2021;
        LocalDate now = LocalDate.of(year, Month.JANUARY, 1);
        // Find the first Sunday of the year
        LocalDate sunday = now.with(firstInMonth(DayOfWeek.SUNDAY));

        do {
            // Loop to get every Sunday by adding Period.ofDays(7) the the current Sunday.
            System.out.println(sunday.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
            sunday = sunday.plus(Period.ofDays(7));
        } while (sunday.getYear() == year);
    }

输出是

Sunday, January 5, 2020 Sunday, January 12, 2020 Sunday, January 19, 2020 Sunday, January 26, 2020 Sunday, February 2, 2020 Sunday, February 9, 2020 Sunday, February 16, 2020 Sunday, February 23, 2020 ... Sunday, December 6, 2020 Sunday, December 13, 2020 Sunday, December 20, 2020 Sunday, December 27, 2020

我怎样才能得到一个月的第一个星期天


共 (3) 个答案

  1. # 1 楼答案

    您可以在每次迭代中添加一个月

    public static void findFirstSundayEachMonth() {
        int year = 2021;
        LocalDate curr = LocalDate.of(year, Month.JANUARY, 1);
        do {
            System.out.println(curr.with(TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY))
               .format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
            curr = curr.plusMonths(1);
        } while (curr.getYear() == year);
    }
    

    Demo

  2. # 2 楼答案

    你可以试着移动这个

    LocalDate sunday = now.with(firstInMonth(DayOfWeek.SUNDAY));
    

    在while中,逐月更新now,而不是每周更新sunday

  3. # 3 楼答案

    溪流

    我们可以用一条小溪在一年中的几个月里循环

    ^{}类代表一年。在传递^{}枚举对象(^{}DECEMBER)时调用^{}返回^{}对象。在传递1时调用^{}返回该月第一个月的^{}对象。我们可以使用^{},特别是来自^{}的那一个,从该月的第一个LocalDate移动到该月的第一个星期天。我们在周日的约会中又得到了一个LocalDate对象

    我们通过调用^{}将每个月派生的第一个星期日LocalDate对象收集到一个列表中。在Java16及更高版本中,我们可以用对^{}的简单调用来替换该列表收集器

    类似这样的代码

    List< LocalDate > firstSundayOfEachMonthInYear =
        Stream.of( Month.values() )
        .map( month -> 
            Year
            .of( 2021 )
            .atMonth( month )
            .atDay( 1 )
            .with( 
                TemporalAdjusters.firstInMonth( DayOfWeek.SUNDAY )
            ) 
        )
        .collect( Collectors.toList() )   // In Java 16+, shorten to: .toList() 
    ;
    

    进口

    import java.util.*;
    import java.lang.*;
    import java.io.*;
     
    import java.time.* ;
    import java.util.stream.* ;
    import java.time.temporal.* ;
    

    看这个code run live at IdeOne.com

    [2021-01-03, 2021-02-07, 2021-03-07, 2021-04-04, 2021-05-02, 2021-06-06, 2021-07-04, 2021-08-01, 2021-09-05, 2021-10-03, 2021-11-07, 2021-12-05]