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

2 Answers

0 votes
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit

object DateTimeDifferenceApp {

  /**
   * Calculates the total number of seconds between two LocalDateTime instances.
   * 
   * @param startDateTime The starting date and time.
   * @param endDateTime The ending date and time.
   * @return Long The total number of seconds.
   */
  def getSecondsBetween(startDateTime: LocalDateTime, endDateTime: LocalDateTime): Long = {
    // ChronoUnit.SECONDS.between efficiently computes the total elapsed seconds
    ChronoUnit.SECONDS.between(startDateTime, endDateTime)
  }

  def main(args: Array[String]): Unit = {
    // Define two LocalDateTime instances
    val dateTime1: LocalDateTime = LocalDateTime.of(2025, 1, 12, 0, 0, 0)
    val dateTime2: LocalDateTime = LocalDateTime.of(2025, 1, 13, 0, 0, 0)

    // Call the function to calculate the seconds difference
    val secondsDifference: Long = getSecondsBetween(dateTime1, dateTime2)

    // Output the results to the console
    println(s"Start Date: $dateTime1")
    println(s"End Date:   $dateTime2")
    println(s"Difference in seconds: $secondsDifference")
  }
}
   
   
/*
run:
     
Start Date: 2025-01-12T00:00
End Date:   2025-01-13T00:00
Difference in seconds: 86400
 
*/

 



answered Jan 13, 2025 by avibootz
edited Oct 27 by avibootz
0 votes
import java.time.{Instant, Duration}

object DateDifferenceApp {

  /**
   * Calculates the total number of seconds between two Instant instances.
   * 
   * @param startDate The starting point in time.
   * @param endDate The ending point in time.
   * @return Double The total number of seconds, preserving fractional sub-second precision.
   */
  def getSecondsBetween(startDate: Instant, endDate: Instant): Double = {
    // Duration.between calculates the time interval between two temporal objects
    val duration: Duration = Duration.between(startDate, endDate)
    
    // Combine full seconds and nanoseconds converted to fractional seconds
    duration.getSeconds.toDouble + (duration.getNano.toDouble / 1_000_000_000.0)
  }

  def main(args: Array[String]): Unit = {
    // Define two Instant instances using ISO-8601 parsing 
    // (best practice for clarity and time-zone safety)
    val startDate: Instant = Instant.parse("2026-10-27T12:00:00Z")
    val endDate: Instant = Instant.parse("2026-10-27T12:05:30Z")

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

    // Output the results to the console
    println(s"Start Date: $startDate")
    println(s"End Date:   $endDate")
    println(s"Total Seconds Between: $totalSeconds")
  }
}


/*
run:

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

*/

 



answered Oct 27 by avibootz
...