java - 将两位数年份转换为四位数字,还支持一位或两位数月份
问题描述
我想将两位数年份转换为四位数字,也可以是 4 位数字
final Integer year = 2020;
final Integer month = 12;
final DateFormat originalFormat = new SimpleDateFormat("MMyy", Locale.US);
final Date monthAndYear = originalFormat.parse(month + String.valueOf(year));
final DateFormat formattedDate = new SimpleDateFormat("yyyy-MM", Locale.US);
System.out.println(formattedDate.format(monthAndYear));
如果输入为 2-2020,则此代码将失败,即不解析一位数月份。
我想通过以下条件传递代码
year | month || expeected
2020 | 12 || "2020-12"
30 | 2 || "2030-02"
41 | 05 || "2041-05"
解决方案
你可以YearMonth
这样使用:
final DateTimeFormatter YEAR_FORMAT = DateTimeFormatter.ofPattern("[yyyy][yy]");
YearMonth yearMonth = YearMonth.of(
Year.parse(year, YEAR_FORMAT).getValue(),
month);
注意:年份应该是一个字符串
输出:
2020-12
2030-02
2041-05
推荐阅读
- excel - 如何根据多重标准和使用 OR 逻辑对值进行计数
- python - 为什么在构建 dict() 时会出现 TypeError?
- node.js - Dialogflow - 多个 agent.add 响应(nodejs)
- r - 为什么我的 anova 不能在闪亮的应用程序中工作
- qt-creator - QtCreator 在启动“文件错误”时崩溃
- amcharts - amcharts - 在图表外使用我自己的按钮导出图表
- python - 如何将数据添加到空 pd.dataframe python
- android - 单元测试,使用 PowerMock 在 Kotlin 中使用 Context 作为变量来模拟静态方法
- node.js - nodejs并发下如何正确使用redis的GET SET命令?
- bash - 将 aws 命令中提取的值分配给 jenkins 管道中的变量