【问题标题】:Convert two digit year to four digits and also support one or two digit month将两位数年份转换为四位数字,还支持一位或两位数月份
【发布时间】: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"

【问题讨论】:

  • 如果你有一年的199999 怎么办?
  • 我需要返回 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


【解决方案1】:

您可以像这样使用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

【讨论】:

    【解决方案2】:

    我认为我不想为此使用解析,尽管这是一个选项。你的年份和月份是数字,所以我觉得这样处理它们更自然。与其他人一样,我建议使用来自 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);
    

    此示例 sn-p 的输出:

    2020-12

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

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

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

    格式为 ISO 8601。

    链接: Wikipedia article: ISO 8601

    【讨论】:

    • 嗨@Ole,为什么你认为当第20年和第4年结果应该是2120-04?不违反OP要求吗?
    • @YCF_L OP 必须做出决定。如果我们要从字面上理解I will get input as future year,你是对的。我相信可以将代码修改为预期的内容。我希望OP能进一步澄清。
    【解决方案3】:

    在格式中使用单个 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
    

    【讨论】:

      【解决方案4】:
      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);
      

      【讨论】:

        猜你喜欢
        • 2011-01-02
        • 1970-01-01
        • 2010-12-11
        • 2016-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多