Java date does not save milliseconds when converting with a simple date format

I am 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 it prints the following:

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

How can I get this date to save milliseconds?

+5
source share
5 answers

The convertDate object actually contains information in milliseconds. The problem here is that the format of the toString () method does not print milliseconds.

Do

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

You can also check if ms are installed with

 System.out.println("millis: " + convertedDate.getTime());
+8
source
 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

+1
source

( , ):

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

:

Jan 13,1970 17:53:13.190

,

+1

TL;DR

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

SJuan76 : Date::toString. java.time.

java.time

java.time, , Date/Calendar.

, ISO 8601. SPACE T.

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

LocalDateTime, --UTC .

LocalDateTime ldt = LocalDateTime.parse( input ) ;

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

SQL

java.sql, . java.time. JDBC 4.2, java.time . , java.sql.Date .

myPreparedStatement.setObject( … , ldt ) ;

...

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

# 1: , .

# 2: java.time. .


java.time

java.time Java 8 . legacy , java.util.Date, Calendar SimpleDateFormat.

Joda-Time, , java.time.

, . Oracle. Qaru . JSR 310.

JDBC-, JDBC 4.2 java.time- . java.sql. * Classes.

java.time?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proof of possible future additions to java.time. Here you can find useful classes, such as Interval, YearWeek, YearQuarterand longer .

+1
source

All Articles