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

2 Answers

0 votes
import Foundation

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

if let startDate = dateFormatter.date(from: "2025-01-12 00:00:00"),
   let endDate = dateFormatter.date(from: "2025-01-13 00:00:00") {
        let differenceInSeconds = endDate.timeIntervalSince(startDate)
        print("Difference in seconds: \(differenceInSeconds)")
} else {
        print("Invalid date format")
}



/*
run:

Difference in seconds: 86400.0

*/

 



answered Jan 13, 2025 by avibootz
0 votes
import Foundation

/**
 * Calculates the total number of seconds between two Date instances.
 * 
 * - Parameters:
 *   - startDate: The starting date and time.
 *   - endDate: The ending date and time.
 * - Returns: The total number of seconds as a TimeInterval (Double), including fractional seconds.
 */
func getSecondsBetween(startDate: Date, endDate: Date) -> TimeInterval {
    // In Swift, subtracting one Date from another (or calling timeIntervalSince) 
    // directly returns the duration in seconds as a Double.
    return endDate.timeIntervalSince(startDate)
}

// --- Complete Program Demonstration ---
func main() {
    // Define two Date instances using ISO8601DateFormatter 
    // (best practice for precise, unambiguous parsing)
    let isoFormatter = ISO8601DateFormatter()
    
    guard let startDate = isoFormatter.date(from: "2026-10-27T12:00:00Z"),
          let endDate = isoFormatter.date(from: "2026-10-27T12:05:30Z") else {
        print("Error: Failed to parse date strings.")
        return
    }

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

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

// Execute the program
main()


/*
run:

Start Date: 2026-10-27 12:00:00 +0000
End Date:   2026-10-27 12:05:30 +0000
Total Seconds Between: 330.0

*/

 



answered Oct 27 by avibootz
...