0

I am writing a small app for a martial arts school. They have classes 5 days a week, at different times. I basically want it so that whenever you look at the class times in the app, it tells you if there is class that day, and if there is, how much time is left until class begins. I have most of it figured out, but I am struggling to figure out how to format the time remaining.

Right now, I can figure out how many hours and minutes are left... but when it comes to formatting those numbers, sometimes they are single digits. So for example - if there is 2 hours and 7 minutes left until a class begins, I WANT it to display:

"Class starts in 02:07"

but instead it displays

"Class starts in 2:7".

Any thoughts on how I can remedy this? In this example, I have class starting at 6:15pm.

I have the following code:

let userCalendar = Calendar.current
let todaysDate = Date()

let currentTimeComponents = userCalendar.dateComponents([.year, .month, .day], from: todaysDate)
let curYear = currentTimeComponents.year
let curMonth = currentTimeComponents.month
let curDay = currentTimeComponents.day
let classTimeComponents = DateComponents(year: curYear, month: curMonth, day: curDay, hour: 18, minute: 15)

let classTime = userCalendar.date(from: classTimeComponents)!

let hoursMinutesBeforeClass = userCalendar.dateComponents([.hour, .minute], from: Date(), to: classTime)
let hrsBeforeClass = hoursMinutesBeforeClass.hour!
let minsBeforeClass = hoursMinutesBeforeClass.minute!

if (hrsBeforeClass > 0 || minsBeforeClass > 0) {
    print("Class starts in \(hrsBeforeClass):\(minsBeforeClass)")
} else {
    print("Class is over tonight. Our next class is tomorrow night.")
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
John Hubler
  • 877
  • 1
  • 11
  • 27
  • Look at the [DateComponentsFormatter](https://developer.apple.com/reference/foundation/datecomponentsformatter"DateComponentsFormatter") – jjatie Nov 14 '16 at 04:59
  • `String(format: "%02d:%02d", hrsBeforeClass, minsBeforeClass)` – Leo Dabus Nov 14 '16 at 05:04
  • @Rmaddy, I disagree with your choice of a duplicate answer. NSDateComponentsFormatter Is a much better choice for formatting time intervals for display than generating time units with leading zeros manually. For one thing it will format the interval correctly for the user's locale. – Duncan C Nov 14 '16 at 05:09
  • @rmaddy According to [WWDC '16 Session 205](https://developer.apple.com/videos/play/wwdc2016/205/ "WWDC '16 Session 205") the correct answer is to use a DateComponentsFormatter – jjatie Nov 14 '16 at 05:11
  • 1
    @DuncanC The OP asked how to show the leading zeros. The duplicate answers that. Using `DateComponentsFormatter` is a fine choice but the OP didn't ask about how to show the remaining time in a format similar to what you would get with that formatter. – rmaddy Nov 14 '16 at 05:13
  • It's an XY problem – Duncan C Nov 14 '16 at 12:03

0 Answers0