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
Asked
Active
Viewed 127 times
2 Answers
5
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.
hd1
- 32,598
- 5
- 75
- 87
0
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.
Arvind Kumar Avinash
- 62,771
- 5
- 54
- 92
-
2And others whinge about it, eh? – hd1 Apr 03 '20 at 16:45