anon
anon

Reputation:

Java dates difference in milliseconds

I've written the following code, but I always just get...

4838399999 Seconds is : 59 Minutes is : 59 Hours is : 23 Days is : 7

Calendar xmas = Calendar.getInstance();
final Calendar now = Calendar.getInstance();

xmas.set(Calendar.YEAR, 2011);
xmas.set(Calendar.MONTH, Calendar.DECEMBER);
xmas.set(Calendar.DAY_OF_MONTH, 25);

long milliseconds1 = now.getTimeInMillis();
long milliseconds2 = xmas.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
System.out.println(diff);
diff = diff / 1000;

final long diffSeconds = diff % 60;
System.out.println("Seconds is : " + diffSeconds);
diff = diff / 60;

final long diffMinutes = diff % 60;
System.out.println("Minutes is : " + diffMinutes);
diff = diff / 60;

final long diffHours = diff % 60;
System.out.println("Hours is : " + diffHours);
diff = diff / 24;

final long diffDays = diff % 24;
System.out.println("Days is : " + diffDays);

Can anyone see anything wrong with this logic to find the days, hours, minutes and seconds till xmas?

Upvotes: 4

Views: 9396

Answers (2)

ruakh
ruakh

Reputation: 183602

These two lines are wrong:

final long diffHours = diff % 60

final long diffDays = diff % 24;

Also, you're not setting the hours/minutes/seconds/milliseconds on xmas, so it gets the hours, minutes, and seconds from the current time. For example, if you run the program at 4:30:20 AM, then it will give you the time until 4:30:20 AM on Christmas. You probably want the time until 00:00:00 on Christmas.

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 285077

When you do:

diff = diff / 1000;

you're permanently losing the remainder. It should be something like:

long seconds = diff / 1000; // seconds is milliseconds / 1000
long milliseconds = diff % 1000; // remainder is milliseconds that are not composing seconds.
long minutes = seconds / 60;
seconds = seconds % 60;
long hours = minutes / 60;
minutes = minutes % 60;

The same pattern of the last four continues.

Upvotes: 7

Related Questions