I have DateTime string 2020-04-03 01:29:27 and 2020-04-03 01:29:37 I want to get duration in hours. I have tried many things but this but cant find any help
2 Answers
I have tried many things but this but cant find any help
Do these "many things" include consulting the javadoc where you would find that:
// assuming both dates are in d1 and d2 Duration duration = Duration.between(d1, d2); long hours = duration.toHours(); Hope that helps.
Comments
java.time
import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Main { public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime dt1 = LocalDateTime.parse("2020-04-03 01:29:27", formatter); LocalDateTime dt2 = LocalDateTime.parse("2020-04-03 01:29:37", formatter); System.out.printf("%.4f Hour(s)", Duration.between(dt1, dt2).toSeconds() / 3600.0); } } Output:
0.0028 Hour(s) Learn more about java.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.
2 Comments
hd1
And others whinge about it, eh?
Arvind Kumar Avinash
@hd1 - I didn't understand your comment. I tried to understand your comment by going through your answer but I couldn't make anything out of your comment. If your comment is about why I have used
.toSeconds() / 3600.0, the answer is: purposefully. Had I used Duration.between(dt1, dt2).toHours(), it would have returned 0.