Java日期在简单日期格式的转换中不保留毫秒 [英] Java date is not preserving milliseconds in conversion with simple date format

查看:90
本文介绍了Java日期在简单日期格式的转换中不保留毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以下字符串2012-04-13 04:08:42.794转换为日期类型:

I'm trying to convert the following string "2012-04-13 04:08:42.794" to a date type:

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");

    Date convertedDate;
    try {
        convertedDate = dateFormat.parse(dateString);
        System.out.println(" in utils: "+convertedDate.toString());
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    }


  //----------------- i think this is the problem
java.sql.Date sqlDate = new java.sql.Date(convertedDate.getTime());
        System.out.println("sql: "+sqlDate.toString());
        return sqlDate;

但是这是打印如下:

in utils: Fri Apr 13 04:08:42 PDT 2012

如何获得这个日期以保留毫秒?

How can I get this date to preserve the milliseconds?

推荐答案

convertDate对象实际上包含毫秒信息。这里的问题是toString()方法格式不打印毫秒。

The convertedDate object does in fact contain the millisecond information. The issue here is that the toString() method format does not print milliseconds.

Do

 System.out.println(" in utils: " + dateFormat.format(convertedDate));

您还可以检查ms是否设置为

You can also check if the ms are set with

 System.out.println("millis: " + convertedDate.getTime());

这篇关于Java日期在简单日期格式的转换中不保留毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆