【问题标题】:Date formatting with Century使用 Century 格式化日期
【发布时间】:2025-12-09 03:30:02
【问题描述】:

我有一种方法可以将包含世纪的日期格式化为通用格式。 将 cyymmdd 中的日期格式化为 MM/dd/yyyy。

例子,

Convert 1140711 to o7/11/2014

【问题讨论】:

    标签: java simpledateformat date-formatting date-conversion


    【解决方案1】:

    如果你说的是转换格式的字符串:

    1140711

    2014 年 7 月 11 日

        DateFormat df1 = new SimpleDateFormat("yyddMM");
        DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy");
        String dateString = "1140711";
    
        System.out.println(df2.format(df1.parse(dateString.substring(1, dateString.length()))));
    

    【讨论】:

      【解决方案2】:

      据我所知,唯一能够处理世纪字段的日期时间库是 Joda-Time。

      LocalDate date = DateTimeFormat.forPattern("CyyMMdd").parseLocalDate("1140711");
      System.out.println("Century=" + date.getCenturyOfEra()); // 20
      String usFormat = DateTimeFormat.forPattern("MM/dd/yyyy").print(date);
      System.out.println(usFormat); // output: 07/11/2014
      

      正如您所见,世纪的输入数字“1”被简单地忽略了,因为 Joda-Time 仅将其他字段评估为有效日期。就个人而言,我会拒绝这样的世纪输入,因为我们在 21 世纪,世纪编号为 20,而不是 1。所以 Joda-Time 在这里有其限制,但你真的确定你的输入中有一个世纪 1,或者这只是一个错字吗?

      【讨论】:

      • 唉,这实际上是某些系统中常见的日期格式
      【解决方案3】:

      我不得不做相反的事情,将日期转换为 cyyMMdd。

          String centuryCharacterOfDateFormat(LocalDate valueDate) {
          int year = valueDate.getYear();
          int yearMinus1900 = year - 1900;
      
          if (yearMinus1900 < 0) {
              throw new PipRuntimeException("Invalid value date, because it is before 1900. " + valueDate);
          } else if (yearMinus1900 < 100) {
              return "0";
          } else {
              String strVal = String.valueOf(yearMinus1900);
              char hundredthChar = strVal.charAt(strVal.length() - 3);
              return String.valueOf(hundredthChar);
          }
      }
      

      您可以使用类似的逻辑进行相反的转换。要获得年份,您可以添加 1900 和数百个第一个字符。

      【讨论】: