Dassi Orleando Dassi Orleando - 2 months ago 10
Java Question

How is really the Java time in millis means?

Please need help to understand this small Java program showing two Java date with different values in long.

Date dateOne = new Date();
long dateOnetime = dateOne.getTime();

long dateTwoTime = dateOnetime / 1000;
dateTwoTime *=1000;

Date dateTwo = new Date(dateTwoTime);

When logging these variable with a simple System.out.println(String str); I got:

  • dateOneTime = 1476976051325

  • dateTwoTime = 1476976051000

  • dateOne = dateTwo = Thu Oct 20 16:07:31 WAT 2016

Why dateOneTime & dateTwoTime are so different but dateTwo is same as dateOne ??

Thanks in advance for clear details.

bwa bwa

Actually there is a difference at the microsecond level in your dates. And that makes the difference.

dateOne and dateTwo are actually not equals. The fact is you are using the toString to assert the equality, which I believe is not the best way to go, because the toString method doesn't take in account the microsecond difference. I'd rather suggest you make use of the dateOne.equals(dateTwo) to make the comparison, as show in the sample I put for you here.

public class TestDate {

    public static void main (String ...args) {
            Date dateOne = new Date();
            long dateOneTime = dateOne.getTime();
            long dateTwoTime = dateOneTime/1000;


            long dateThreeTime = dateTwoTime*1000;

            dateTwoTime *= 1000;

            Date dateTwo = new Date(dateTwoTime);
            if(dateOne.equals(dateTwo)) {
                    System.out.println("Dates are equals");
            } else {
                    System.out.println("Dates are not equals");