iosswiftdatetimensdatenstimer

Swift countdown timer labels for Days/Hours/Minutes/Seconds


I'm creating a countdown timer that counts down to an NSDate set in a UIDatePicker. I have a label that shows the date we're counting down to and that works fine.

What I'm also trying to add is labels for the number of whole days left and number of hours/minutes/seconds left in the current day (i.e. never more than 23/59/59) Here's what I've done at the minute but it obviously shows the values for the whole countdown. Hoping someone can help me work out the correct logic here.

let secondsLeft = sender.date.timeIntervalSinceDate(NSDate())
hoursLabel.text = String(secondsLeft % 3600)
minutesLabel.text = String((secondsLeft / 60) % 60)
secondsLabel.text = String(secondsLeft % 60)

I guess what I'm looking for is some swift equivalent of the datetime class you get in php


Solution

  • Take a look at the NSCalendar class. Specifically look at the method components:fromDate:toDate:options: That lets you take 2 dates and calculate the difference between them using whatever units you specify.

    It's also localizable, so if you use the current calendar and the user uses the Chinese, Hebrew, or Arabic calendar then the calculations will give you results correct for that calendar.