Java Online Compiler
Example: Calculate the Difference Between Two Time Periods in Java Using LocalDateTime
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// DIFFERENCE BETWEEN TWO TIME PERIODS in Java using LocalDateTime import java.util.Scanner; import java.time.LocalDateTime; import java.time.Duration; public class Main { public static void main(String[] args) { // Step-1 Define two LocalDateTime objects LocalDateTime startTime = LocalDateTime.of(2025, 5, 1, 10, 30, 0); LocalDateTime endTime = LocalDateTime.of(2025, 5, 9, 15, 45, 0); // Step-2 Calculate duration between the two time periods Duration duration = Duration.between(startTime, endTime); // Step-3 Extract hours, minutes, and seconds from the duration long totalSeconds = duration.getSeconds(); long hours = totalSeconds / 3600; long minutes = (totalSeconds % 3600) / 60; long seconds = totalSeconds % 60; // Step-4 Display the result System.out.println("\nTIME DIFFERENCE: " + hours + " HOURS, " + minutes + " MINUTES, " + seconds + " SECONDS"); } }
Output
Clear
ADVERTISEMENTS