【发布时间】:2020-06-25 11:03:58
【问题描述】:
我想将两位数年份转换为四位数字,也可以是四位数字
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"
【问题讨论】:
-
如果你有一年的
1999或99怎么办? -
我需要返回 1999 年。但就我而言,它将是未来一年
-
在
41的示例中,您期望2041为什么99您期望1999? -
对于 99, 2099 是可以的。但如果它是 1999 年,则需要返回 1999 年。对于我的情况,我将作为未来年份获得输入
-
我编辑了我的答案,对于你的情况
YearMonth yearMonth = YearMonth.of(Year.parse("2022", YEAR_FORMAT).getValue(), 5);它适用于我的代码
标签: java date datetime simpledateformat date-format