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?
The Date class in Java internally stores Date in milliseconds. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and the Date class provides a constructor which can be used to create Date from milliseconds. The SimpleDateFormat class helps in formatting and parsing of data.
Once you have the Date object, you can get the milliseconds since the epoch by calling Date. getTime() . The full example: String myDate = "2014/10/29 18:10:45"; //creates a formatter that parses the date in the given format SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = sdf.
millis(); System. out. println(milliSeconds); Output:: 1534749202051 Explanation:: when millis() is called, then it returns a current instant of Class Object in milliseconds.
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
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());
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With