Duration d = Duration.between(fromDateTime, toDateTime); long days = d.toDays(); long seconds = d.toSeconds();
Duration d = Duration.between(fromDateTime, toDateTime); long days = d.toDays(); long seconds = d.toSeconds(); long days = ChronoUnit.DAYS.between(fromDateTime, toDateTime); long seconds = ChronoUnit.SECONDS.between(fromDateTime, toDateTime);
long days = ChronoUnit.DAYS.between(fromDateTime, toDateTime); long seconds = ChronoUnit.SECONDS.between(fromDateTime, toDateTime); long days = fromDateTime.until(toDateTime, ChronoUnit.DAYS); long days = fromDateTime.until(toDateTime, ChronoUnit.SECONDS); Difference between 2 timestamps in a multiple parts with different units
It's "semi-manual" because you'll need to write some form of algorithm to get order right (the manual part) but can still use read-to-use calculations like plusXxx() and until() (the automatic part).
Duration d = Duration.between(fromDateTime, toDateTime); long days = d.toDaysPart(); long seconds = d.toSecondsPart();
Duration d = Duration.between(fromDateTime, toDateTime); long days = d.toDaysPart(); long seconds = d.toSecondsPart(); - Units above days are not supported as of Java 21
- Units in between will be missed, i.e. the example above will return 10859 days from
toDaysPart()but only 50 seconds fromtoSecondsPart()so you'd miss 22 hours and 54 minutes in between. UsingTemporal.until()as in my original answer gives you the ability to express the example duration as "10859 days and 82490 seconds"
Manual calculations
A final option that _may_ be faster than the others(albeit probably very negligible) would be to calculate everything yourself. The basic idea is to get the milliseconds between the 2 dates and then do your calculations. For sake of simplicity I'll use Duration.toMillis() but there are other options as well which might be faster.
long millis = Duration.between(fromDateTime, toDateTime).toMillis(); long millisPerDay = 24 * 60 * 60 * 1000; //24 hours * 60 minutes * 60 seconds * 1000 millis long days = millis / millisPerDay; //example yields 10859 long seconds = millis / 1000; //example yields 938300090 Notes:
- This may be the fastest calculation and be sufficient for simple use cases
- If you're using larger units like months or years you may need to take length differences into account (months range from 28 to 31 days, years from 365 to 366 days, etc.) which would make this more complex and especially error prone