Home > Software engineering >  Calculate number of milliseconds between two times
Calculate number of milliseconds between two times

Time:10-18

I'm trying to calculate how many milliseconds between two times (for example between 13:00 to 13:01 there are 60000 milliseconds). The times are represented by 2 integers (hour, minute).

I wrote this function:

public static long millisBetweenTimes(int h1, int m1, int h2, int m2) { //hour1, minute1, hour2, minute2
      long millis;
      millis = (h2 - h1) * (60 * 60000);
      if (m < tm)
        millis  = (m2 - m1) * 60000;
      else
        millis -= (m1 - m2) * 60000;
      return millis;
}

However, this won't work when the second time is the day after (e.g. how many milliseconds between 14:00 Sunday to 13:00 Monday?)

CodePudding user response:

As Robby already said in the comments, you should use classes from the java.time package. With the classes LocalTime and Duration, you could get the milliseconds between two points in time.

LocalTime t0 = LocalTime.of(14, 0);
LocalTime t1 = LocalTime.of(13, 0);
Duration d = Duration.between(t0, t1);
if (d.isNegative()) {
    d = d.plusDays(1);
}
System.out.println(d.toMillis());

A Duration is a, well, duration: the length of time between two points in time. If the second time lies before the first, then the duration is negative. In such case, we need to add 1 day to the duration.

Now we have an amount of time represented by the Duration class. This class contains many methods to convert it to a certain time unit. In our case, toMillis() is exactly what we need.

Online demo

Instead of d.isNegative(), you can also use t1.isBefore(t0), if you think it's more expressive.


Note: I think this is not as half as clumsy as doing the math yourself.

CodePudding user response:

Your approach would only work in a single 24 hour cycle as you are passing in two hour integers and subtracting them. So if you are calculating the amount of milliseconds from 13:00 to 14:00 tomorrow the second time input needs to be 25:00 as 24 hours have passed. Another way you can approach this is by using java dates and taking out the hour from the day you want to start and finish.

  •  Tags:  
  • java
  • Related