How to get the difference between two dates in seconds with Java

2 Answers

0 votes
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 dateTime1 = LocalDateTime.parse("2025-01-12 00:00:00", formatter);
        LocalDateTime dateTime2 = LocalDateTime.parse("2025-01-13 00:00:00", formatter);

        Duration duration = Duration.between(dateTime1, dateTime2);

        long secondsDifference = duration.getSeconds();

        System.out.println("Difference in seconds: " + secondsDifference);
    }
}



/*
run:

Difference in seconds: 86400
 
*/

 



answered Jan 13, 2025 by avibootz
0 votes
import java.time.LocalDateTime;
import java.time.Duration;

public class DateDifferenceApp {

    /**
     * Calculates the total number of seconds between two LocalDateTime instances.
     * 
     * @param startDate The starting date and time.
     * @param endDate The ending date and time.
     * @return long The total number of seconds.
     */
    public static long getSecondsBetween(LocalDateTime startDate, LocalDateTime endDate) {
        // Duration.between calculates the time interval between two temporal objects
        Duration duration = Duration.between(startDate, endDate);
        
        // Return the total elapsed seconds as a long
        return duration.getSeconds();
    }

    public static void main(String[] args) {
        // Define two LocalDateTime instances using clear factory methods (best practice)
        LocalDateTime startDate = LocalDateTime.of(2026, 10, 27, 12, 0, 0);
        LocalDateTime endDate = LocalDateTime.of(2026, 10, 27, 12, 5, 30);

        // Call the function to calculate the seconds between the two dates
        long totalSeconds = getSecondsBetween(startDate, endDate);

        // Output the results to the console
        System.out.println("Start Date: " + startDate);
        System.out.println("End Date:   " + endDate);
        System.out.println("Total Seconds Between: " + totalSeconds);
    }
}


/*
run:

Start Date: 2026-10-27T12:00
End Date:   2026-10-27T12:05:30
Total Seconds Between: 330

*/

 



answered Oct 27 by avibootz
...