Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift timeInterval formatter

Tags:

date

macos

swift

I can get the date in de date picker, calculate the time left and put in a label. This gives seconds:

let timeLeft = datePicker.dateValue.timeIntervalSinceNow
countingLabel.stringValue = "seconds left: \(timeLeft)"

How to format "timeLeft"?

I tried this and it does not work:
var formatter = NSDateFormatter()
formatter.dateFormat = "EEEE, yyyy-MM-dd hh:mm:ss"
let timeLeft2 = formatter.stringFromDate(timeLeft)
like image 472
Nrc Avatar asked May 14 '15 14:05

Nrc


1 Answers

You can use NSDateComponentsFormatter. From the documentation:

An NSDateComponentsFormatter object takes quantities of time and formats them as a user-readable string. Use a date components formatter to create strings for your app’s interface.

Example:

let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Full
formatter.allowedUnits = .CalendarUnitSecond | .CalendarUnitMinute | .CalendarUnitHour

let pickedDate = datePicker.dateValue
let now = NSDate()
let formattedTimeLeft = formatter.stringFromDate(now, toDate: pickedDate)!

// Example result : 1:06:50

There are some more output formats available, e.g.

.Abbreviated :  1h 6m 50s
.Short :        1 hr, 6 min, 50 secs
.Full :         1 hour, 6 minutes and 50 seconds

Update for Swift 4 and later:

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full // or .short or .abbreviated
formatter.allowedUnits = [.second, .minute, .hour]

let pickedDate = datePicker.date
let now = Date()
let formattedTimeLeft = formatter.string(from: now, to: pickedDate)!
like image 102
Martin R Avatar answered Nov 15 '22 05:11

Martin R