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.")
}