Swift: DatePicker-Timer?

Viewed 95

Hey!

Here's my problem:

So I have a datepicker which is primarily used to send messages when the set time is reached. However, I would like to see the time run out (timer-like) until the time is reached. Best in the format (hh:mm:ss), because the datepicker is set in the timer format.

I am only a beginner in programming. So I don't know what to do :/

I would be very happy if someone could help me!

Many thanks in advance.

     let date = NSDate()
     let calendar = Calendar.current

     let components = calendar.dateComponents([.hour, .minute, .month, .year, .day], from: 
     date as Date)

     let currentDate = calendar.date(from: components)

     let userCalendar = Calendar.current

     let competitionDate = self.datepicker.isSelected

     let competition = userCalendar.date(from: competitionDate as DateComponents)!

     let CompetitionDifference = calendar.dateComponents([.hour, .minute, .second], from: 
     currentDate!, to: competition)


     let hoursLeft = CompetitionDifference.hour
     let minutesLeft = CompetitionDifference.minute
     let secondsLeft = CompetitionDifference.second

     print("hours:", hoursLeft ?? "N/A", "minutes:", minutesLeft ?? "N/A", "seconds:", 
     secondsLeft ?? "N/A")

    countDownLabel.text = "\(daysLeft ?? 0) hours, \(hoursLeft ?? 0) minutes, \(minutesLeft 
    ?? 0) seconds"
1 Answers

First, you just can't write :

let competition = userCalendar.date(from: competitionDate as DateComponents)!

it will just trigger an error if competitionDate is not a DateComponents but say, a Date!

Then, if you just want string representations of quantities of time DateComponentsFormatter is for you

try :

let date = Date()
let calendar = Calendar.current
let userCalendar = Calendar.current

let competitionDate = date + 4899
let comps = userCalendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: competitionDate)



let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.string(from: date, to: competitionDate) // "1 hour, 21 minutes, 39 seconds"
formatter.unitsStyle = .short
formatter.string(from: date, to: competitionDate) // "1 hr, 21 min, 39"secs"
formatter.unitsStyle = .brief
formatter.string(from: date, to: competitionDate) // "1hr 21min 39secs"
formatter.unitsStyle = .abbreviated
formatter.string(from: date, to: competitionDate) // "1h 21m 39s"
formatter.unitsStyle = .positional
formatter.string(from: date, to: competitionDate) // "1:21:39"
formatter.includesTimeRemainingPhrase = true
formatter.string(from: date, to: competitionDate) // "1:21:39 remaining"

Related