Java的SimpleDateFormat用毫秒/微秒做什么?

时间:2015-10-30 16:48:40

标签: java date simpledateformat milliseconds

我有简单的测试

@SuppressWarnings("deprecation")
@Test
public void test_NO_MILLIS() throws ParseException {
    String rabbit = "22-OCT-15 06.37.35";
    final String PATTERN = "dd-MMM-yy HH.mm.ss";
    Date dateObject = new SimpleDateFormat(PATTERN).parse(rabbit);
    Assert.assertNotNull(dateObject);
    Assert.assertEquals(22, dateObject.getDate());
    Assert.assertEquals(10, dateObject.getMonth() + 1);
    Assert.assertEquals(2015, dateObject.getYear() + 1900);
    Assert.assertEquals(6, dateObject.getHours());
    Assert.assertEquals(37, dateObject.getMinutes());
    Assert.assertEquals(35, dateObject.getSeconds());
}

一切顺利。我的结果是22天。

但是我在模式和要解析的字符串值之后添加微秒

    @Test
public void test_MILLIS() throws ParseException {
    String rabbit = "22-OCT-15 06.37.35.586173000";
    final String PATTERN = "dd-MMM-yy HH.mm.ss.SSSSSSSSS";
    Date dateObject = new SimpleDateFormat(PATTERN).parse(rabbit);
    Assert.assertNotNull(dateObject);
    Assert.assertEquals(22, dateObject.getDate());
    Assert.assertEquals(10, dateObject.getMonth() + 1);
    Assert.assertEquals(2015, dateObject.getYear() + 1900);
    Assert.assertEquals(6, dateObject.getHours());
    Assert.assertEquals(37, dateObject.getMinutes());
    Assert.assertEquals(35, dateObject.getSeconds());
}

我得到断言失败

junit.framework.AssertionFailedError: expected:<22> but was:<29>
at junit.framework.Assert.fail(Assert.java:57)
at junit.framework.Assert.failNotEquals(Assert.java:329)
at junit.framework.Assert.assertEquals(Assert.java:78)
at junit.framework.Assert.assertEquals(Assert.java:234)
at junit.framework.Assert.assertEquals(Assert.java:241)
at main.TestDateFormatTest.test_MILLIS(TestDateFormatTest.java:36)
...

这意味着那一天变成了29而不是22.出了什么问题? 经测试 平台:mac osx 10.9,ubuntu,win7 jdk:7,6

1 个答案:

答案 0 :(得分:4)

格式模式S(毫秒)并未考虑数学放置值;它只是将586173000视为要添加到剩余日期的毫秒数。这个数字相当于大约6.784天,这就解释了为什么日期变为29而不是22。

在解析之前,切掉3位数的毫秒数,例如"22-OCT-15 06.37.35.586",因此它被解释为586毫秒。