将两位数年份转换为四位数,还支持一位或两位数月份

Convert two digit year to four digits and also support one or two digit month

我想把两位数的年份转成四位,也可以变成四位

        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
String pattern = "";
        if(year1.length() == 4){
            pattern = "yyyy";
        }elif(year1.length() == 2){
            pattern = "yy[yy]";
        }
        
        YearMonth yearMonth = YearMonth.of(Year.parse(year1, DateTimeFormatter.ofPattern(pattern)).getValue(),month);  
        System.out.println(yearMonth);

在格式中使用单个 M 表示一个月。单个 M 适用于 modern date-time API 中一个月内任何允许的数字位数。您应该停止使用损坏和过时的 java.util 日期时间 API 并切换到现代日期时间 API.

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M-[uuuu][uu]");

        // Test strings (month-year)
        String[] ymStrArr = { "2-2020", "2-20", "02-2020", "02-20" };
        for (String ymStr : ymStrArr) {
            YearMonth ym = YearMonth.parse(ymStr, formatter);
            System.out.println(ym);
        }
    }
}

输出:

2020-02
2020-02
2020-02
2020-02

我认为我不想为此使用解析,尽管这是一个选项。你的年月都是数字,所以我觉得这样处理它们更自然。像其他人一样,我建议使用 java.time 中的 YearMonth,现代 Java 日期和时间 API。

    final Integer year = 2020;
    final Integer month = 12;
    
    YearMonth monthAndYear;
    if (0 <= year && year < 100) { // two digits
        YearMonth currentMonthAndYear = YearMonth.now(ZoneId.systemDefault());
        // Truncate current year to whole centuries
        int fullYear = currentMonthAndYear.getYear() / 100 * 100 + year;
        monthAndYear = YearMonth.of(fullYear, month);
        if (monthAndYear.isBefore(currentMonthAndYear)) { // in the past, wrong
            monthAndYear = monthAndYear.plusYears(100);
        }
    } else {
        monthAndYear = YearMonth.of(year, month);
    }
    
    System.out.println(monthAndYear);

此示例片段的输出:

2020-12

它比其他答案中的代码更冗长。好处是它可以让我们精确控制两位数年份使用哪个世纪。第 20 年和第 4 个月给我们 2120-04,而第 20 年和第 9 个月给我们 2020-09。所以两者都是未来。

您想将结果作为您问题格式的字符串吗?我们很幸运,YearMonth.toString() 给了我们。

    System.out.println(monthAndYear.toString());

格式为 ISO 8601。

Link: Wikipedia article: ISO 8601