Find the difference in seconds between NSDates as a whole using Swift

I am writing a piece of code where I want to tell how long the button was held. To do this, I wrote NSDate() when I pressed the button and tried to use the timeIntervalSinceDate function when the button was released. This seems to work, but I cannot find a way to print the result or switch it to an integer.

 var timeAtPress = NSDate() @IBAction func pressed(sender: AnyObject) { println("pressed") timeAtPress = NSDate() } @IBAction func released(sender: AnyObject) { println("released") var elapsedTime = NSDate.timeIntervalSinceDate(timeAtPress) duration = ??? } 

I saw several similar questions, but I don’t know C, so it was difficult for me to understand the answers. If there is a more efficient way to find out how long a button has been held, I am open to suggestions. Thanks in advance.

+75
swift nsdate nstimeinterval
Oct 28 '14 at 0:44
source share
6 answers

Your attempt to calculate elapsedTime is incorrect. In Swift 3, it will be:

 let elapsed = Date().timeIntervalSince(timeAtPress) 

Note () after the Date link. Date() creates a new date object, and then timeIntervalSince returns the time difference between that and timeAtPress . This will return a floating point value (technically, TimeInterval ).

If you want this to be truncated to an Int value, you can simply use:

 let duration = Int(elapsed) 

And, BTW, your timeAtPress variable timeAtPress does not need to instantiate a Date object. I assume you intended:

 var timeAtPress: Date! 

Defines a variable as a Date variable (implicitly expanded), but you are supposed to postpone the actual creation of this variable until pressed is called.




Alternatively, I often use CFAbsoluteTimeGetCurrent() , for example,

 var start: CFAbsoluteTime! 

And when I want to set startTime , I do the following:

 start = CFAbsoluteTimeGetCurrent() 

And when I want to calculate the number of seconds elapsed, I do the following:

 let elapsed = CFAbsoluteTimeGetCurrent() - start 



It is worth noting that the CFAbsoluteTimeGetCurrent documentation warns us:

Repeated calls to this function do not guarantee monotonically increasing results. System time may be reduced due to synchronization with external time references or due to a user explicitly changing the clock.

This means that if you are fortunate enough to measure the elapsed time, when one of these adjustments occurs, you can complete the wrong time calculation. This is also true for NSDate / Date calculations. It is mach_absolute_time use calculations based on mach_absolute_time (most easily done using CACurrentMediaTime ):

 let start = CACurrentMediaTime() 

and

 let elapsed = CACurrentMediaTime() - start 

In this case, mach_absolute_time used, but avoids some of its complexities outlined in Technical Q & A QA1398 .

Remember that when the device is rebooted, CACurrentMediaTime / mach_absolute_time will be reset. So, on the bottom line, if you need accurate calculations of elapsed time while the application is CACurrentMediaTime , use CACurrentMediaTime . But if you are going to keep this start time in a permanent storage that you could remember when the application is restarted on some future day, then you should use Date or CFAbsoluteTimeGetCurrent and just live with any inaccuracies that may entail.

+171
Oct 28 '14 at 1:11
source share
β€” -

NSDate () and NSCalendar () sound like a good choice. Use the calculation of the calendar and leave the actual mathematical part in the framework. Here is a brief example of getting seconds between two NSDate()

 let startDate = NSDate() let endDate = NSDate() let calendar = NSCalendar.currentCalendar() let dateComponents = calendar.components(NSCalendarUnit.CalendarUnitSecond, fromDate: startDate, toDate: endDate, options: nil) let seconds = dateComponents.second println("Seconds: \(seconds)") 
+21
Oct 28 '14 at 2:03
source share

According to Freddy's answer, this is a feature in quick 3:

 let start = Date() let enddt = Date(timeIntervalSince1970: 100) let calendar = Calendar.current let unitFlags = Set<Calendar.Component>([ .second]) let datecomponenets = calendar.dateComponents(unitFlags, from: start, to: enddt) let seconds = datecomponenets.second print("Seconds: \(seconds)") 
+3
Aug 2 '17 at 16:00
source share

Here's how you can get the difference in the latest version of Swift 3

 let calendar = NSCalendar.current var compos:Set<Calendar.Component> = Set<Calendar.Component>() compos.insert(.second) compos.insert(.minute) let difference = calendar.dateComponents(compos, from: fromDate, to: toDate) print("diff in minute=\(difference.minute!)") // difference in minute print("diff in seconds=\(difference.second!)") // difference in seconds 

Link: Getting the difference between two NSDate's (months / days / hours / minutes / seconds)

0
Jul 29 '17 at 22:38
source share

Swift 5

  let startDate = Date() let endDate = Date() let calendar = Calendar.current let dateComponents = calendar.compare(startDate, to: endDate, toGranularity: .second) let seconds = dateComponents.rawValue print("Seconds: \(seconds)") 
0
Apr 16 '19 at 8:35
source share

For Swift 3 Seconds between 2 times in "hh: mm"

 func secondsIn(_ str: String)->Int{ var strArr = str.characters.split{$0 == ":"}.map(String.init) var sec = Int(strArr[0])! * 3600 var sec1 = Int(strArr[1])! * 36 print("sec") print(sec+sec1) return sec+sec1 } 

Using

 var sec1 = secondsIn(shuttleTime) var sec2 = secondsIn(dateToString(Date())) print(sec1-sec2) 
-5
Feb 22 '17 at 9:27
source share



All Articles