-2

I want do calculate the difference between two timestamps in Java.

I've found this answer: https://stackoverflow.com/a/5351516/6719146

long diffSeconds = diff / 1000 % 60;  
long diffMinutes = diff / (60 * 1000) % 60;

on stackoverflow.

My question is: why is there the % (Modulo Operator)?

Community
  • 1
  • 1
BukkitDEV
  • 3
  • 4

1 Answers1

0

The answer you found is answering a different question.

Your question is:

I want do calculate the difference between two timestamps in Java.

The question answered by the code you refer to is:

I want to calculate difference between 2 dates in hours/minutes/seconds.

(emphasis mine)

The % operation is used to separate seconds from minutes and hours.

In other words, the other question talks about 3 numbers, the hour, the minute and the second. All need to be extracted from the the single number - the milliseconds elapsed between 2 moments of time.

Suppose the difference between two times is 1995 seconds.

The number you begin with is 1995000 .

If all you want is a number of milliseconds between two times, then all you need is to print the number: "1995000 milliseconds elapsed". But this is not too useful.

A more useful output would be: "Time elapsed: 0:33:15 seconds".

Please consider how you would come up with the numbers 33 and 15. Hint: % is involved.