【问题标题】:List of "Year-Month" from Current Year month to Jan-2021 in JavaJava中从当年月份到2021年1月的“年月”列表
【发布时间】:2022-02-14 14:33:28
【问题描述】:

我有一个业务需求来编写一个服务,它返回从 01-2021 到当前年份月份(当前:02-2022)的年份月份列表(01-2021,02-2021,....) .

谁能建议我在 Java 8 中解决这个问题的方法

O/P : 01-2021, 02-2021, 03-2021, 04-2021, 以此类推, 02-2022.

【问题讨论】:

  • 我会看看java.time 包中的YearMonth 类:for (YearMonth ym = YearMonth.of(2021, 1); !ym.isAfter(YearMonth.now()); ym=ym.plusMonths(1)) { ... }
  • 嗯,您可以使用YearMonth.plusMonths 获取任何给定 YearMonth 的下一个,YearMonth.now 获取当前的,YearMonth.compareTo 将一个YearMonth 与另一个进行比较...我希望这足以让您入门。

标签: java datetime java-8 jodatime


【解决方案1】:

如下所示。

YearMonth now = YearMonth.now();
YearMonth ym = YearMonth.of(2021, 1);
List<YearMonth> list = new ArrayList<>();
while (!ym.isAfter(now)) {
  list.add(ym);
  ym = ym.plusMonths(1);
}
DateTimeFormatter format = DateTimeFormatter.ofPattern("MM-yyyy");
List<String> list2 = list.stream().map(it -> it.format(format)).collect(Collectors.toList());

应该会给你一份从 2021-1 到现在的清单。

另一种选择是使用流。

DateTimeFormatter format = DateTimeFormatter.ofPattern("MM-yyyy");
long months = Period.between(LocalDate.of(2021, 1, 1), LocalDate.now()).toTotalMonths();
List<String> yms = LongStream.rangeClosed(0, months)
  .mapToObj(it -> YearMonth.now().minusMonths(it))
  .map(it -> it.format(format))
  .collect(Collectors.toList());

您首先计算月数,迭代该数字并生成列表。

【讨论】:

  • 这就是你从头脑中输入内容得到的结果:|。固定。
  • 谢谢!!上面的代码有效,但在邮递员中我看到以下格式 ["2021-01","2021-02","2021-03","2021-04","2021-05","2021-06", ,"2021-07","2021-08","2021-09","2021-10","2021-11","2021-12","2022-01","2022-02"],但是前端需要的是01-2021,02-2021,这种格式
  • 添加map 并转换为String 列表,您看到的是toString 或YearMonth。我已经编辑了答案以将其考虑在内。
【解决方案2】:

java.time 包有一个 YearMonth 类 (documentation) 非常适合此用例:

for (YearMonth ym = YearMonth.of(2021, Month.JANUARY); // or ...of(2021, 1)
     !ym.isAfter(YearMonth.now());
     ym = ym.plusMonths(1))
{
    System.out.printf("%Tm-%1$TY\n", ym);
}

【讨论】:

    【解决方案3】:
    import java.time.*;
    import java.time.format.DateTimeFormatter;
    public class YearMonth {
        public static void getYearMonths() {
    
            YearMonth nextMonth = YearMonth.now().plusMonths(1);
            YearMonth yearMonth = YearMonth.of(2021, 01);
     
            while (nextMonth.isAfter(yearMonth)) {
            // Create a DateTimeFormatter string
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-yyyy");
            
            // Format this year-month
            System.out.println(yearMonth.format(formatter));
            yearMonth = yearMonth.plusMonths(1);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多