使用 LocalDate 获取过去的一周和一年

Get Week and Year in Past Using LocalDate

我正在使用 Java 8 时间库来确定从今天开始的前几周和前一年,然后将这些值存储在地图中。我想我已经想出了如何正确地获得星期,但我不完全确定获得年份的正确方法是什么。当前代码如下:

int weeksLimit = 5; // this value is passed into the method, but just setting it here as an example
Map<Integer, Integer> yearWeeks = new HashMap<Integer, Integer>();
LocalDate ld = LocalDate.now();
WeekFields weekFields = WeekFields.of(DayOfWeek.SUNDAY, 4);
for (int i = weeksLimit; i > 0; i--) {
    LocalDate pastDate = ld.minusWeeks(i);
    yearWeeks.put(pastDate.getYear(), pastDate.get(weekFields.weekOfWeekBasedYear()));
}

我不认为 pastDate.getYear() 是正确的用法。结果我想要的是:

有人可以帮我弄清楚如何正确获得我想要的年份吗?[=​​12=]

我无法判断哪种数据结构适合您的目的。以年为键、以周为值的地图无法保存您的示例数据。在您的示例中,2020 年出现了三次,但给定的键在地图中只能出现一次。在下面的示例中,我假设一个地图将基于年份的每个星期映射到该年份的 list 周数。

    WeekFields weekFields = WeekFields.of(Locale.forLanguageTag("mt_MT"));

    int weeksLimit = 5; // this value is passed into the method, but just setting it here as an example

    LocalDate today = LocalDate.now(ZoneId.of("Europe/Malta"));
    Map<Integer, List<Integer>> yearWeeks = IntStream.rangeClosed(1, weeksLimit)
            .mapToObj(i -> today.minusWeeks(i))
            .collect(Collectors.groupingBy(ld -> ld.get(weekFields.weekBasedYear()),
                    Collectors.mapping(ld -> ld.get(weekFields.weekOfWeekBasedYear()),
                            Collectors.toList())));

    System.out.println(yearWeeks);

当我运行刚才的片段时,输出是:

{2019=[52, 51], 2020=[3, 2, 1]}

我不希望在那里,但在我更清楚地了解您的要求之前,我不会为此付出更多努力。