【问题标题】:SimpleDateFormatter does not recognize monthsSimpleDateFormat 无法识别月份
【发布时间】:2011-05-13 13:09:44
【问题描述】:

我想解析一个日期字符串,但失败得很惨。 为了说明我的问题,我编写了这个简单的 JUnit 测试:

@Test
public void testParseJavaDate() throws ParseException {     
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD_HH-mm-ss", Locale.GERMAN);

    String inputtime = "2011-04-21_16-01-08";
    Date parse = sdf.parse(inputtime);

    assertEquals(inputtime,sdf.format(parse));
}

此测试失败并显示以下消息:

org.junit.ComparisonFailure: 预期: 但是是:

我不明白为什么格式化程序无法正确解析日期。你有什么想法吗?

【问题讨论】:

    标签: java parsing date


    【解决方案1】:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.GERMAN);

    String inputtime = "2011-04-21_16-01-08";
    Date parse = sdf.parse(inputtime);
    

    使用 dd 代替 DD。

    【讨论】:

      【解决方案2】:

      你想要“dd”(一个月中的一天),而不是“DD”(一年中的一天):

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.GERMAN);
      

      【讨论】:

        【解决方案3】:

        使用d 而不是D,因为D 是“一年中的日期”,因此月份必须与一年中的第21 天(即一月)匹配。

        【讨论】:

          【解决方案4】:

          前面的都是对的,但你也必须用'mm'代替'MM',反之亦然 因为 'M' 显示分钟,必要时带有前导零

          所以你的代码如下

          public void testParseJavaDate() throws ParseException {
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd_HH-MM-ss", Locale.GERMAN);
          
              String inputtime = "2011-04-21_16-01-08";
              Date parse = sdf.parse(inputtime);
          
              sdf = new SimpleDateFormat("dd/mm/yyyy HH:MM:ss", Locale.GERMAN);
          
              System.out.println(sdf.format(parse));
          
              assertEquals(inputtime, sdf.format(parse));
          }
          

          它会打印出来

          run: 21/04/2011 16:01:08 BUILD SUCCESSFUL (total time: 0 seconds)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-20
            • 2016-06-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多