在Java中将带有毫秒的字符串简洁地转换为日期类型失败



请查收以下代码:

@RunWith(JUnit4.class)
public class TestTimestamp {
    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss.SSSSSS");
    private final static SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
    @Test
    public void test() throws ParseException {
        getTimestamp("20140512 16:13:09.493166 +0800", sdf);
        getTimestamp("20140515 15:04:42.690873 +0800", sdf);
        getTimestamp("20140515 15:04:45.159977 +0800", sdf);
        getTimestamp("20140512 16:13:09.493166 +0800", df);
        getTimestamp("20140515 15:04:42.690873 +0800", df);
        getTimestamp("20140515 15:04:45.159977 +0800", df);
    }
    private void getTimestamp(String time, SimpleDateFormat sdf) throws ParseException {
        System.out.println("Time to convert: " + time);
        String[] tmp = time.split("\+");
        String str = tmp[0].trim();
        System.out.println(str);
        System.out.println(sdf.parse(str));
        System.out.println();
    }
}

sdf的输出很奇怪,df的输出是正确的:

//Wrong result with sdf
Time to convert: 20140512 16:13:09.493166 +0800
20140512 16:13:09.493166
Mon May 12 16:21:22 CST 2014
Time to convert: 20140515 15:04:42.690873 +0800
20140515 15:04:42.690873
Thu May 15 15:16:12 CST 2014
Time to convert: 20140515 15:04:45.159977 +0800
20140515 15:04:45.159977
Thu May 15 15:07:24 CST 2014

//Correct result with df
Time to convert: 20140512 16:13:09.493166 +0800
20140512 16:13:09.493166
Mon May 12 16:13:09 CST 2014
Time to convert: 20140515 15:04:42.690873 +0800
20140515 15:04:42.690873
Thu May 15 15:04:42 CST 2014
Time to convert: 20140515 15:04:45.159977 +0800
20140515 15:04:45.159977
Thu May 15 15:04:45 CST 2014

你能帮我吗?

1毫秒相当于SSS的千分之一。159977的长度将超过1微秒

yyyyMMdd HH:mm:ss.SSS

java.util.Date和Joda-Time都具有毫秒级精度。所以他们只能处理三位数的分数。要么截断分数的最后三位数字,要么使用新的java。Java 8中的time包,可以处理纳秒精度(9位)。

相关内容

  • 没有找到相关文章

最新更新