Momro
Momro

Reputation: 981

Avoid Rounding Error on Double -> Date conversion

In my program, I receive strings that define a time stamp in milliseconds. Now I need to convert this to a proper date. The solution I found looks something like this:

String aTime = "1365504203.0269";
double t = Double.parseDouble(aTime);

Date date = new Date((long)t*1000);
SimpleDateFormat dateFormatDDMMYYYY = new SimpleDateFormat("dd.MM.yyyy");
SimpleDateFormat dateFormatHHMMssSS = new SimpleDateFormat("HH:mm:ss:SS");
String day = new String(dateFormatHHMMssSS.format(date));
String hour = new String(dateFormatDDMMYYYY.format(date));

System.out.println("The Date: "+day);
System.out.println("The Time: "+hour);

Unfortunately, this removes the accuracy of milliseconds from the time stamp. (I'm not sure if the time is even that accurate as I can hardly think about it anymore.)

Has it gone lost due to double->long conversion, or has it never been there at all? Any way to workaround this problem?

Upvotes: 0

Views: 169

Answers (1)

le3th4x0rbot
le3th4x0rbot

Reputation: 2461

The problem is in this statement:

Date date = new Date((long)t*1000);

It casts the double to a long first, thereby truncating the decimal places, and then multiplies by 1000, which just adds three zeros. Try this:

Date date = new Date((long)(t*1000.0));

It uses double as the data type for multiplication, which moves the decimal places into the integer part, and then makes the decimal place truncating long conversion.

Using 1000.0 instead of 1000 as the constant forces the constant to be of double type as well, adding an extra level of certainty that the multiplication will happen with doubles.

Upvotes: 3

Related Questions