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

2 Answers

0 votes
import java.time.LocalDateTime
import java.time.Duration

fun main() {
    val startDateTime = LocalDateTime.of(2025, 1, 12, 0, 0, 0)
    val endDateTime = LocalDateTime.of(2025, 1, 13, 0, 0, 0)

    val duration = Duration.between(startDateTime, endDateTime)
    val secondsDifference = duration.seconds

    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

/**
 * 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.
 */
fun getSecondsBetween(startDate: LocalDateTime, endDate: LocalDateTime): Long {
    // Duration.between computes the time interval between two temporal objects
    return Duration.between(startDate, endDate).seconds
}

fun main() {
    // Define two LocalDateTime instances using clear factory methods (best practice for readability)
    val startDate = LocalDateTime.of(2026, 10, 27, 12, 0, 0)
    val endDate = LocalDateTime.of(2026, 10, 27, 12, 5, 30)

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

    // Output the results to the console
    println("Start Date: $startDate")
    println("End Date:   $endDate")
    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
...