5

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;

But this is printing the following:

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

How can I get this date to preserve the milliseconds?

Atma
  • 29,141
  • 56
  • 198
  • 299
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Mar 10 '18 at 06:15

5 Answers5

9

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));

You can also check if the ms are set with

 System.out.println("millis: " + convertedDate.getTime());
SJuan76
  • 24,532
  • 6
  • 47
  • 87
  • I think the problem is that I convert to sql date. Will this get rid of milliseconds? – Atma Apr 14 '12 at 00:35
  • No, `DateFormat.parse()` returns a `java.util.Date`, not a `java.sql.Date`. What is happening is that `java.util.Date.toString()` uses a format that does not show the milliseconds, but the data is in the object. Do the prints that I told you in my answer and you will see the millisecond info. http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html#parse(java.lang.String) – SJuan76 Apr 14 '12 at 10:11
1
 Calendar now = Calendar.getInstance();
 System.out.println("Current milliseconds since Jan 1, 1970 are :"
              + now.getTimeInMillis());

just use java.util.Calendar http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
emilan
  • 12,825
  • 11
  • 32
  • 37
1

He's my go at it (trying to keep the same code style as yours) :

import java.util.*;
import java.text.*;
public class main {
 public static void main(String[] args)throws Exception {
 long yourmilliseconds = 1119193190;
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss.SSS");

Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));  } 
}  

Output :

Jan 13,1970 17:53:13.190

Regards, Erwald

Erwald
  • 2,118
  • 2
  • 14
  • 20
1

Instead of printing using toString() you can make your own printing method, so it prints the information you want specifically. Also note that most of the Date class is deprecated - look at http://docs.oracle.com/javase/6/docs/api/java/util/Date.html

Mads
  • 724
  • 3
  • 10
1

tl;dr

myPreparedStatetment.setObject( 
    … ,
    LocalDateTime.parse(
        "2012-04-13 04:08:42.794".replace( " " , "T" )
    )
)

Details

The Answer by SJuan76 is correct: You are being fooled by the poorly-designed output of the Date::toString method. Instead, use java.time classes.

java.time

The modern approach uses the java.time classes that supplanted the troublesome old date-time classes such as Date/Calendar.

First convert your input string to fully comply with the ISO 8601 standard. Replace the SPACE in the middle with a T.

String input = "2012-04-13 04:08:42.794".replace( " " , "T" ) ;

Parse as a LocalDateTime since your input lacks an indicator of offset-from-UTC or time zone.

LocalDateTime ldt = LocalDateTime.parse( input ) ;

ldt.toString(): 2012-04-13T04:08:42.794

SQL

Avoid the date-time related java.sql classes. They too are supplanted by the java.time classes. As of JDBC 4.2, you can directly exchange java.time objects with your database. So you can forget all about the java.sql.Date class and its terrible hacked design.

myPreparedStatement.setObject( … , ldt ) ;

And…

LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;

Morals

Moral of the story # 1: Use smart objects, not dumb strings.

Moral of the story # 2: Use only java.time objects. Avoid legacy date-time classes.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154