0

I'm new in programming and I'm planning to add a countdown in my app. However, when the values under 10, it turns not 09 but only 9. I want to turn every value under 10 as 09, 08. I mean with 0.

Here is my code for countdown. I already managed to add 0 for minutes but I don't know how to affect all variables together. Thanks in advance.

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute, .Month, .Year, .Day, .Second], fromDate: date)
_ = components.hour
_ = components.minute
_ = components.month
_ = components.year
_ = components.day
_ = components.second

let currentDate = calendar.dateFromComponents(components)

// I set here the due date. When the timer is supposed to finish
let userCalendar = NSCalendar.currentCalendar()

let competitionDate = NSDateComponents()
competitionDate.year = 2016
competitionDate.month = 5
competitionDate.day = 22
competitionDate.hour = 10
competitionDate.minute = 00
competitionDate.second = 00
let competitionDay = userCalendar.dateFromComponents(competitionDate)!

// I compare the two dates
competitionDay.timeIntervalSinceDate(currentDate!)

let dayCalendarUnit: NSCalendarUnit = ([. Month, .Day, .Hour, .Minute, . Second])

//I change here the seconds to hours,minutes and days
let CompetitionDayDifference = userCalendar.components( dayCalendarUnit, fromDate: currentDate!,toDate: competitionDay, options: [])
//Here I set the variable to our remaining time
let monthsLeft = CompetitionDayDifference.month
let daysLeft = CompetitionDayDifference.day
let hoursLeft = CompetitionDayDifference.hour
let minutesLeft = CompetitionDayDifference.minute
let secondsLeft = CompetitionDayDifference.second

if hoursLeft < 10 {
      allinoneLabel.text = String("0\(monthsLeft)  :  \(daysLeft)  :  0\(hoursLeft)  :  \(minutesLeft)  :  \(secondsLeft)")
}else {
     allinoneLabel.text = String("0\(monthsLeft)  :  \(daysLeft)  :  \(hoursLeft)  :  \(minutesLeft)  :  \(secondsLeft)")
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Bucky Ak
  • 37
  • 1
  • 3
  • Use [NSNumberFormatter](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/index.html) – ryantxr May 01 '16 at 22:24
  • 2
    `allinoneLabel.text = String(format: "%02d : %02d : %02d : %02d : %02d", monthsLeft, daysLeft, hoursLeft, minutesLeft, secondsLeft)` – vacawama May 01 '16 at 23:27

0 Answers0