Reputation: 871
I've got a method to parse a String (yyyy-MM-dd HH:mm:ss.SSS) to 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 in 0, eg "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 output is the following 2013-07-07 19:15:00.0
Is there any way to keep my precision of three decimal places on the Milliseconds? I realise I could probably do some sort of length check and manually add on 0's, but a more efficient, standard way of keeping this precision would be preferred
Upvotes: 4
Views: 20846
Reputation: 328727
The precision is not lost: the trailing zeros are simply truncated.
You can verify it 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
Upvotes: 3