首页 > 解决方案 > 将两位数年份转换为四位数字,还支持一位或两位数月份

问题描述

我想将两位数年份转换为四位数字,也可以是 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"

标签: javadatedatetimesimpledateformatdate-format

解决方案


你可以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

推荐阅读