Harish Aravind Harish Aravind - 5 months ago 9
Java Question

Java: milliseconds parsed wrongly when converted from string to timestamp

I have trouble while parsing the given string into a timestamp.
The milliseconds is parsed wrongly or let me know if I am missing something.

I get a string from the request as:

String selectedTimeStamp = request.getParameter("selectTime");
System.out.println("selectedTimeStamp: "+selectedTimeStamp);


and then I use simpleDateFormat to parse and format the string:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
Date parsedDate = sdf.parse(selectedTimeStamp);
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
System.out.println("createdTime: " +timestamp);


The output I get is:

selectedTimeStamp: 2016-07-04 21:09:47.66
createdTime: 2016-07-04 21:09:47.066


Not sure why the millisecond is converted from 66 to 066 ? It should be 660
any idea?

Answer

Let's break it down step-by-step

Your code(effectively)

String selectedTimeStamp = "2016-07-04 21:09:47.6";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
Date parsedDate = sdf.parse(selectedTimeStamp);

System.out.println("parsedDate: " + parsedDate);

Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
System.out.println("createdTime: " +timestamp);

I am assuming that these are the imports you have made:

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

The output of which is

parsedDate: Mon Jul 04 21:09:47 IST 2016

createdTime: 2016-07-04 21:09:47.006

So even though I passed 6 ms as argument, it got parsed to 600 ms, this is most likely due to the fact that we are using, java library for parsing date and sql library for time stamping it. The process for treating date objects is different in both the languages, hence the inconsistency. Also millisecond is treated with a number of 1000th precision(as 1000ms = 1s) therefore SQL automatically converts the Java stored 6 to 006 (or 66 to 066 in your case).

I simple workaround this problem will be to check selectedTimeStamp using selectedTimeStamp.length() - selectedTimeStamp.lastIndexOf('.') and concatenating the remaining zeroes, i.e. if it is 2 then 2 zeroes, if 3 then 1 zero, and if 4 then no zeroes.

This will give you correct result.

Add this after the String selectesTimeStamp = "2016-07-04 21:09:47.6" line

int x = selectedTimeStamp.length() - selectedTimeStamp.lastIndexOf('.');

if (x==2)
    selectedTimeStamp += "00";
if (x==3)
    selectedTimeStamp += '0';

Cheers!!!

P.S.: Changing SSS to SS will not work.