Kashif Jilani
Kashif Jilani

Reputation: 1257

Find difference in two dates in iOS

I am not sure what I am doing wrong, I need to find difference between two dates and extract seconds from it, below is my code. I am not getting correct seconds. There is difference of seconds.

  public func captureStartTime() {
    captureStartDateTime = Date()
  }

  public func captureEndTime(eventType: String, eventElement: String) {
    let difference = Date().timeIntervalSince(captureStartDateTime)
    let interval = Int(difference)
    let seconds = interval % 60
    let secondsDescrp = String(format: "%02d", seconds)
}

Upvotes: 6

Views: 5669

Answers (4)

Mike Zriel
Mike Zriel

Reputation: 1865

Simple Function:

func dateDiff(from: Date, to: Date) -> Int {
    return Calendar.current.dateComponents([.second], from: from, to: to).second ?? 0
}

Example:

 let lastLogin = Date()
 if dateDiff(from: lastLogin, to: Date()) < 30 { return }

Upvotes: 0

Kaushik Kapadiya
Kaushik Kapadiya

Reputation: 9

you can also use default date components and according to that compare your dates and you can get the difference in year, month, day etc

let dateString1 =  "2019-03-07T14:20:20.000Z"

let dateString2 =  "2019-03-07T14:20:40.000Z"



//set date formate

let Dateformatter = DateFormatter()

Dateformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"



//convert string to date

let dateold = Dateformatter.date(from: dateString1)!

 let datenew = Dateformatter.date(from: dateString2)!



 //use default datecomponents with two dates

 let calendar1 = Calendar.current

 let components = calendar1.dateComponents([.year,.month,.day,.hour,.minute,.second], from:  dateold, to:   datenew)



 let seconds = components.second

 print("Seconds: \(seconds)")

Upvotes: 0

AtulParmar
AtulParmar

Reputation: 4570

Use the following code to get the difference between two dates, Store current time in startTime when pressed button 1 and store current date time in endTime when pressed button 2, See this code, I hope this helps you.

var startTime:Date!
var endTime:Date!

@IBAction func buttonStartTime(_ sender: UIButton) {
    startTime = Date()
}


@IBAction func buttonEndTime(_ sender: UIButton) {
    endTime = Date()

    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.second]
    formatter.unitsStyle = .full
    let difference = formatter.string(from: startTime, to: endTime)!
    print(difference)//output "8 seconds"
}

Output

8 seconds

Upvotes: 1

rmaddy
rmaddy

Reputation: 318774

interval is the answer you want. That is the total number of seconds between the two dates.

Your seconds value would only be useful if you wanted to calculate the number of hours, minutes, and seconds or the number of minutes and seconds from the total number of seconds.

Upvotes: 5

Related Questions