Reputation:
This question has probably been answered before. But here I go.
I have a String object with value "21:48" and another String object with value "23:23". How can I calculate the milliseconds between these two times?
Upvotes: 0
Views: 2613
Reputation: 2873
Using Java time, you can obtain the total amount of milliseconds between two date-time objects by creating a Duration
object.
Duration duration = // TODO
long millis = duration.toMillis();
You did specify 21:48
and 23:23
as String
input values. You can use the LocalTime
class to represent this concept of hours, minutes and seconds.
LocalTime lt1 = LocalTime.parse("21:48");
LocalTime lt2 = LocalTime.parse("23:23");
Duration ldd = Duration.between(lt1, lt2);
long millis = duration.toMillis(); // 5700000
Please note that this Duration
only relates to the LocalTime
. If you want to measure the real amount of milliseconds, you have to consider that time-zones may apply daylight saving time.
// in Germany, for example, at 2020-10-25 on 03:00 clocks are turned backward 1 hour
ZoneId berlin = ZoneId.of("Europe/Berlin");
LocalDateTime ldt1 = LocalDateTime.of(LocalDate.parse("2020-10-24"), lt1);
LocalDateTime ldt2 = LocalDateTime.of(LocalDate.parse("2020-10-25"), lt2);
ZonedDateTime zdt1 = ZonedDateTime.of(ldt1, berlin);
ZonedDateTime zdt2 = ZonedDateTime.of(ldt2, berlin);
// does not consider DST (one hour is missing)
Duration d1 = Duration.between(ldt1, ldt2);
long ms1 = d1.toMillis(); // 92100000
// does consider DST (extra hour applied)
Duration d2 = Duration.between(zdt1, zdt2);
long ms2 = d2.toMillis(); // 95700000
Upvotes: 3
Reputation: 34677
Using Joda-Time:
DateTime zero = new DateTime(time);
long millis = new org.joda.time.Period(DateTime.now()).toDurationFrom(zero).getMillis();
Upvotes: -1
Reputation: 79620
You can do it using the modern date-time API as shown below:
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
long millis = LocalTime.parse("21:48").until(LocalTime.parse("23:23"), ChronoUnit.MILLIS);
System.out.println(millis);
}
}
Output:
5700000
Learn more about the modern date-time API at Trail: Date Time.
Upvotes: 3