时间戳转换的问题

时间:2016-04-26 15:12:06

标签: java date parsing simpledateformat java-6

这是我在Java 1.6中的代码(问题被标记为重复,但建议的解决方案是指java 1.8)

public static void main(String[] args){
    try{
        String dateTimeString = "2015-08-10-14.20.40.679279";
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSSSSS");
        java.util.Date formattedDate = dateFormat.parse(dateTimeString);
        Timestamp formattedTime = new Timestamp(formattedDate.getTime());
        System.out.println(formattedTime);
    } catch (Throwable t){
        t.printStackTrace();
    }
}

结果对象是:2015-08-10 14:31:59.279,所以在解析分钟,秒和毫秒时显然有问题,我只是不知道到底是什么。
谢谢!

2 个答案:

答案 0 :(得分:2)

没有类似SSSSSS的东西。 查看Simple Date Format manual

答案 1 :(得分:1)

你必须退出最后3毫秒:

Date d = ( new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS", Locale.US) ).parse("2015-08-10-14.20.40.679279");
        System.out.println(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.S").format(d));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SS").format(d));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS").format(d));

        Date dd = ( new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS", Locale.US) ).parse("2015-08-10-14.20.40.679");
        System.out.println(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.S").format(dd));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SS").format(dd));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS").format(dd));

获得正确的格式:

2015-08-10-14.31.59.279
2015-08-10-14.31.59.279
2015-08-10-14.31.59.279
2015-08-10-14.20.40.679
2015-08-10-14.20.40.679
2015-08-10-14.20.40.679

请查看此playground

相关问题