如何在 java 中获取年份变化的日期

How to get date with year change in java

我的方法有以下字段 - id、年和月。

Collection<User> userCollection = getUserForMonth(int id, int year, int month);

用户给我日期范围。在 fromTimestamp 和 toTimestamp 之间。我必须使用 getUserForMonth 方法,但我不知道如何动态更改这些参数(年和月)。

我从时间戳开始和结束数据都是这样

LocalDate startDate = new Timestamp(csvRaportTransport.getFromTimestamp()).toLocalDateTime().toLocalDate();
LocalDate endDate = new Timestamp(csvRaportTransport.getToTimestamp()).toLocalDateTime().toLocalDate();

我可以像getStartDate一样设置年和月,但我不知道如何切换。

我虽然想了但是怎么变年月了?不知道。 你能帮帮我吗?

如果你想获取 startDate 和 StartYear 之间所有月份的所有用户,你可以这样做:

    LocalDate startDate = LocalDate.of(2018, 01, 1);
    LocalDate endDate = LocalDate.of(2018, 03, 1);
    while(startDate.isBefore(endDate))
    {
        getUserForMonth(123,startDate.getYear(), startDate.getMonthValue());
        startDate = startDate.plusMonths(1);//.plusYears if you want years
    }

如果你想获取特定月份的用户与开始日期和结束日期的关系,你可以使用:

    LocalDate startDate = LocalDate.of(2018, 01, 1);
    LocalDate endDate = LocalDate.of(2018, 03, 1);

    getUserForMonth(123,startDate.getYear(), startDate.getMonthValue());
    getUserForMonth(123,endDate.getYear(), endDate.getMonthValue());

希望对您有所帮助。 正如用户 xxxvodnikxxx 所提到的,您可以在他的评论

中提供的 LocalDate javadoc 中阅读更多相关信息

要获取日期范围内的所有月份,请使用

    public List<LocalDate> getMonthsBetween(LocalDate startDate, LocalDate endDate) {
        long numOfMonthsBetween = ChronoUnit.MONTHS.between(startDate, endDate);
        if(numOfMonthsBetween == 0){
        // means that start and end dates are in the same month
            return Collections.singletonList(startDate);
        }
        return IntStream.iterate(0, i -> i+1)
            .limit(numOfMonthsBetween)
            .mapToObj(i -> startDate.plusMonths(i))
            .collect(Collectors.toList());
    }

然后你可以遍历日期

getMonthsBetween(LocalDate.now(),LocalDate.now().plusMonths(11)).stream()
        .forEach(System.out::println);

这会被骂

2018-03-26
2018-04-26
2018-05-26
2018-06-26
2018-07-26
2018-08-26
2018-09-26
2018-10-26
2018-11-26
2018-12-26
2019-01-26

只需在 forEach 中调用您的 getUserForMonth(int id, int year, int month) 获取每个月的结果并将 sub-result 添加到您计划 return

的最终集合中