How do you calculate the difference between two Date objects in Java?

Asked 1 years ago, Updated 1 years ago, 119 views

We are using Java's java.util.Date class to calculate the difference between the current time and the specific Date object in the scalar. We know that the difference can be calculated using the getTime() method as follows.

(new java.util.Date()).getTime() - oldDate.getTime()

By the way, this result is the number of milliseconds of the Long type. Is there a simple better way to get the time difference?

date timedelta java time scala

2022-09-22 21:37

1 Answers

The API for JDK's Date class is a definition designed when Java was first created. So there are a lot of functions that are lacking. I recommend using the Joda Time library.

Joda Time defined the concept of time interval.:

Interval interval = new Interval(oldTime, new Instant());

Joda has two concepts: Interval (for example, the time between 8 a.m. and 10 a.m.) to express the time interval between two time objects and Duration (for example, 2 hours!) to express the time length without actual time boundaries.

If you just want to calculate the time difference, you can use most Date classes that implement the Compatible interface using CompareTo().


2022-09-22 21:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.