I have two date like:
String date_1="yyyyMMddHHmmss";
String date_2="yyyyMMddHHmmss";
I want to print the difference like:
2d 3h 45m
How can I do that? Thanks!
I have two date like:
String date_1="yyyyMMddHHmmss";
String date_2="yyyyMMddHHmmss";
I want to print the difference like:
2d 3h 45m
How can I do that? Thanks!
When you use
Date()
to calculate the difference in hours is necessary configure theSimpleDateFormat()
in UTC otherwise you get one hour error due to Daylight SavingTime.Here is the modern answer. It’s good for anyone who either uses Java 8 or later (which doesn’t go for most Android phones yet) or is happy with an external library.
This prints
In my own opinion the advantage is not so much that it is shorter (it’s not much), but leaving the calculations to an standard library is less errorprone and gives you clearer code. These are great advantages. The reader is not burdened with recognizing constants like 24, 60 and 1000 and verifying that they are used correctly.
I am using the modern Java date & time API (described in JSR-310 and also known under this name). To use this on Android, get the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project. To use it with other Java 6 or 7, get ThreeTen Backport. With Java 8 and later it is built-in.
With Java 9 it will be still a bit easier since the
Duration
class is extended with methods to give you the days part, hours part, minutes part and seconds part separately so you don’t need the subtractions. See an example in my answer here.out put is :
It will give you difference in months
This works and convert to String as a Bonus ;)