What's the most standard, performant way of figuring out how many days ago a particular java.util.Date object represents? Ideally, I want to get back a double representing the (potentially) fractional number of days ago.
3 Answers
That sounds remarkably like:
(System.currentTimeMillis() - date.getTime()) / (24 * 60 * 60 * 1000d);
In other words, find out the difference between the current time and the given date in millis, and then divide by the number of milliseconds in a day. I've explicitly made the 1000d a double literal to make the final division work in double arithmetic.

- 1,421,763
- 867
- 9,128
- 9,194
-
1I haven't even finished reading the question, and there, you have the answer already. :) – limc Feb 02 '11 at 02:53
java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time
, the modern Date-Time API:
You can use java.time.Duration
, which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation, to find the duration between two instants. Also, avoid performing calculations yourself if you already have a standard API to do the job.
import java.time.Duration;
import java.time.Instant;
public class Main {
public static void main(String[] args) {
// A sample date-time in the past
String strDateTime = "2020-09-10T10:20:30.123456789Z";
Instant past = Instant.parse(strDateTime);
Instant now = Instant.now();
Duration duration = Duration.between(past, now);
long durationInMillis = duration.toMillis();
double days = (double) durationInMillis / Duration.ofDays(1).toMillis();
System.out.println(days);
}
}
Output from a sample run:
299.14329884259257
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

- 71,965
- 6
- 74
- 110
-
1Indeed, that is simpler! Even though the number of function calls is the same, the original solution needed one more type. Updated the answer to incorporate it. Thanks, @OleV.V. for the valuable suggestion – Arvind Kumar Avinash Jul 06 '21 at 15:37
Get System.currentTimeMillis()
and find Date from it. Then get day
, month
, year
. Now it should be easy find difference.

- 39,895
- 28
- 133
- 186