I’m trying to fetch timestamp values from a database, convert them to Calendar, and convert them back to Timestamp, but they lose their precision.
Here’s the code to reproduce the problem
import java.sql.Timestamp;
import java.util.Calendar;
public class Test {
public static void main(String[] args)
{
Timestamp timestamp = new Timestamp(112, 10, 5, 15, 39, 11, 801000000);
System.out.println("BEFORE "+timestamp.toString());
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp.getTime());
timestamp = new Timestamp(calendar.getTimeInMillis());
System.out.println("AFTER "+timestamp.toString());
}
}
Here is the sample result of conversion
BEFORE 2012-10-18 14:30:13.362001
AFTER 2012-10-18 14:30:13.362
It loses its precision.
What do I do to keep the decimal value as it is?
You are setting the time in milliseconds, but your input precision is in microseconds, so of course you are going to lose any precision finer than milliseconds.
Calendar doesn’t support finer granularity than milliseconds. There is no work-around.