首页 > 解决方案 > 创建 X 个日期的算法

问题描述

目前我有一个以 yyyyMM 格式表示日期的字符串列表,如下所示:

我需要在此列表中创建 x 个条目,每个条目将月份增加一个,因此如果我要创建 3 个新条目,它们将如下所示:

目前我的想法是创建一个方法来选择最新日期,解析字符串以分隔月份和年份,如果月份值 < 12 则将月份值增加 1,否则将其设置为 1 并改为增加年份。然后我将该值添加到列表中并将其设置为最新的,重复 x 次。

我想知道是否有更优雅的解决方案可以使用,可能使用现有的日期库(我正在使用 Java)。

标签: javaalgorithmdatecalendaryearmonth

解决方案


YearMonthDateTimeFormatter

我建议您使用这些现代日期时间类来执行此操作,如下所示:

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Test
        List<String> list = getYearMonths("202011", 3);
        System.out.println(list);

        // Bonus: Print each entry of the obtained list, in a new line
        list.forEach(System.out::println);
    }

    public static List<String> getYearMonths(String startWith, int n) {
        List<String> list = new ArrayList<>();

        // Define Formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMM");

        // Parse the year-month string using the defined formatter
        YearMonth ym = YearMonth.parse(startWith, formatter);

        for (int i = 1; i <= n; i++) {
            list.add(ym.format(formatter));
            ym = ym.plusMonths(1);// Increase YearMonth by one month
        }
        return list;
    }
}

输出:

[202011, 202012, 202101]
202011
202012
202101

在Trail: Date Time了解有关现代日期时间 API 的更多信息。


推荐阅读