elcadro
elcadro

Reputation: 1492

Java Calendar add hour issue getting time in millis

I have this snippet here:

    Calendar cal = Calendar.getInstance();
    System.out.println("calendar " + cal.getTime());
    System.out.println("ms calendar" + cal.getTime().getTime());
    long ms0 = cal.getTime().getTime();
    cal.add(Calendar.HOUR, -1);
    System.out.println("calendar one hour less " + cal.getTime());
    System.out.println("ms calendar one hour less " + cal.getTime().getTime());
    long ms1 = cal.getTime().getTime();
    cal.setTimeInMillis(t0-t1);
    System.out.println("result " + cal.getTime());

I was expecting to have just one hour of difference between the two dates. Instead of that I'm getting this weird result:

calendar Wed Sep 23 09:51:36 CEST 2015
ms calendar 1442994696681
calendar one hour less Wed Sep 23 08:51:36 CEST 2015
ms calendar one hour less 1442991096681
result Thu Jan 01 02:00:00 CET 1970

What am I getting wrong? How should I get just one hour of difference, as I see in the Dates?

Any kind of help would be much appreciated. Thanks in advance.

Upvotes: 1

Views: 160

Answers (1)

David Herrero
David Herrero

Reputation: 714

System.out.println("milis restantes:"+ (ms0-ms1));

Result in:

milis restantes:3600000

Your program is working as desired

EDIT:
With you edited question, you need to understand that Calendar starts to count milis from epoch, witch in this case is : Thu Jan 01 01:00:00 CET 1970 So adding an hour to this date will result in Thu Jan 01 02:00:00 CET 1970

If you want to check this behaviour:

cal.setTimeInMillis(0);
  System.out.println("result new Calendar " + cal.getTime());

Result:

result new Calendar Thu Jan 01 01:00:00 CET 1970

Upvotes: 5

Related Questions