Find difference in two dates in iOS

5.3k Views Asked by At

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)
}
3

There are 3 best solutions below

3
rmaddy On

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.

0
AtulParmar On

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

0
Kaushik Kapadiya On

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)")