Sample code for 30+ languages & platforms
Swift

Compute Difference Between Two DateTime Strings

Demonstrates how to compute the difference between two datetime strings.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    // Imagine we have these strings:

    var t1: String? = "2022-11-14 15:45:38"
    var t2: String? = "2022-11-16 17:23:41"

    // How many minutes are between the two?

    // First, we'd want load each date/time into a Chilkat CkDateTime object.
    // In this case, there are no CkDateTime methods that accept the above format.
    // However.. the CkDateTime's SetFromTimestamp will accept a date in the format "YYYY-MM-DDThh:mm:ssZ"

    // First modify the above dates to the timestamp format.
    let sb1 = CkoStringBuilder()!
    sb1.append(value: t1)
    var count: Int = sb1.replace(value: " ", replacement: "T").intValue
    sb1.append(value: "Z")

    let sb2 = CkoStringBuilder()!
    sb2.append(value: t2)
    count = sb2.replace(value: " ", replacement: "T").intValue
    sb2.append(value: "Z")

    // Load each into a CkDateTime
    let dt1 = CkoDateTime()!
    dt1.set(fromTimestamp: sb1.getAsString())
    // verify...
    print("\(dt1.get(asTimestamp: false)!)")

    let dt2 = CkoDateTime()!
    dt2.set(fromTimestamp: sb2.getAsString())
    // verify...
    print("\(dt2.get(asTimestamp: false)!)")

    // Get the difference in seconds
    var diffSeconds: Int = dt2.diffSeconds(dateTimeArg: dt1).intValue
    print("Difference in seconds: \(diffSeconds)")
    print("Difference in minutes: \(diffSeconds / 60)")

}