java - 创建 X 个日期的算法
问题描述
目前我有一个以 yyyyMM 格式表示日期的字符串列表,如下所示:
- 202008
- 202009
- 202010
我需要在此列表中创建 x 个条目,每个条目将月份增加一个,因此如果我要创建 3 个新条目,它们将如下所示:
- 202011
- 202012
- 202101
目前我的想法是创建一个方法来选择最新日期,解析字符串以分隔月份和年份,如果月份值 < 12 则将月份值增加 1,否则将其设置为 1 并改为增加年份。然后我将该值添加到列表中并将其设置为最新的,重复 x 次。
我想知道是否有更优雅的解决方案可以使用,可能使用现有的日期库(我正在使用 Java)。
解决方案
YearMonth
和DateTimeFormatter
我建议您使用这些现代日期时间类来执行此操作,如下所示:
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 的更多信息。
推荐阅读
- r - 如何将公式作为字符串传递?
- python - 在列表中找到重复的单词并从列表中删除该单词
- scala - 如何通过 spark 写入数据并获得聚合时间?
- javascript - 单击锚点时如何停止悬停?
- javascript - 如果输入有值,如何将输入标签放在顶部
- ios - IOS - 当滑块值改变时设置 UILabel Swift
- haskell - 特定函数名称“it”会发生什么?
- asp.net-core - 如何在 .NET Core - Web API 中根据文化显示正确的资源语言?
- c# - C# Linq - 根据用户输入创建动态选择查询
- git - Git忽略文件仍列在未跟踪列表中