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)
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)!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With