Fast countdown timer marks for days / hours / minutes / seconds

I am creating a countdown timer that counts down to the NSDate set in the UIDatePicker . I have a shortcut that shows the date we are counting on, and it works great.

What I'm also trying to add is labels for the number of days left and the number of hours / minutes / seconds remaining in the current day (i.e. no more than 23/59/59). Here is what I did in a minute, but it clearly displays the values ​​for the whole countdown. Hoping someone can help me work out the right 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 assume I'm looking for some quick equivalent of the datetime class that you get in php

+4
source share
2 answers

Take a look at the NSCalendar class. In particular, look at the components:fromDate:toDate:options: method components:fromDate:toDate:options: This allows you to take 2 dates and calculate the difference between them using any units you specify.

It is also localized, so if you use the current calendar and the user uses the Chinese, Hebrew or Arabic calendar, then the calculations will lead to the correct results for this calendar.

+1
source

Got it - for Swift 2

 let calendar = NSCalendar.currentCalendar() let components = calendar.components([.Day, .Hour, .Minute, .Second], fromDate: NSDate(), toDate: sender.date, options: []) daysLabel.text = String(components.day) hoursLabel.text = String(components.hour) minutesLabel.text = String(components.minute) secondsLabel.text = String(components.second) 
+9
source

Source: https://habr.com/ru/post/1242821/


All Articles