SimpleDateFormat to Timestamp loses precision using the getTime () method

I have a method to parse a String (yyyy-MM-dd HH: mm: ss.SSS) for a Date object using SimpleDateFormat.

public static Timestamp convertToTimestamp(String stringToFormat) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); try { Date date = dateFormat.parse(stringToFormat); Timestamp tstamp = new Timestamp(date.getTime()); return tstamp; } catch (ParseException e) { return null; } } 

However, when the milliseconds end with 0, for example, "2013-07-07 19: 15: 00.000", when I do the following to assign it to a Timestamp object:

 Timestamp tstamp = new Timestamp(date.getTime()); 

The conclusion is as follows: 2013-07-07 19: 15: 00.0

Is there a way to keep my precision of three decimal places in milliseconds? I understand that I could probably do some length checking and manually add to 0, but a more efficient, standard way to maintain this precision would be preferable

+4
source share
1 answer

Accuracy is not lost: trailing zeros are simply truncated.

You can check this with:

 Date dt = new Date(); dt.setTime(123); //123 milliseconds Timestamp tstamp = new Timestamp(dt.getTime()); System.out.println("tstamp = " + tstamp); dt.setTime(0); //0 milliseconds => truncated tstamp = new Timestamp(dt.getTime()); System.out.println("tstamp = " + tstamp); 

which prints:

 tstamp = 1970-01-01 01:00:00.123 tstamp = 1970-01-01 01:00:00.0 
+3
source

Source: https://habr.com/ru/post/1492742/


All Articles