1
votes

Let's say I need to get the hours and minutes between two NSDates. For example, one date is 3 hours and 42 minutes after the other. How would I get both hours and minutes of the time elapsed? I've tried something like this, according to this question, but it hasn't worked: you don't get both hours and minutes.

I've also tried using the NSCalendar, but that didn't work out either. Instead, it just gave me the amount of hours and the amount of seconds, instead of making it one measurement.

Any Ideas?

3
This answer stackoverflow.com/a/27182410/1187415 to the referenced question should work, you can specify exactly which units you want, in your case .CalendarUnitMinute | .CalendarUnitHour.Martin R
Is NSTimeInterval adequate? Can you give an example of your expected result?Joe Smith

3 Answers

5
votes

Mac OS X 10.10 Yosemite introduces the smart NSDateComponentsFormatter to display time intervals in components like 18h 56m 4s

This result of this snippet is the formatted time interval from midnight until now.

let calendar = NSCalendar.currentCalendar()
let midnight = calendar.startOfDayForDate(NSDate())
let timeinterval = NSDate().timeIntervalSinceDate(midnight)

let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Abbreviated
formatter.stringFromTimeInterval(timeinterval)
5
votes

The interval is in seconds - that gives you both hours and minutes. Just math a little bit.

let hours = totalTime / 3600
let minutes = (totalTime % 3600) / 60
4
votes

It's easy withplain maths, without needing the calendar.

let now = NSDate()
let latest = NSDate(timeInterval: 3*3600+42*60, sinceDate: now)

let difference = latest.timeIntervalSinceDate(now)

let hours = Int(difference) / 3600
let minutes = (Int(difference) / 60) % 60

This will give you the interval in hours and minutes. Note: Don't forget to cast to integer, as NSTimeInterval is a floating type.