rgoncalv rgoncalv - 16 days ago 4x
iOS Question

Date format Swift 3.0

I have the following code

var calendar = Calendar.current

let unitFlags = Set<Calendar.Component>([.hour, .year, .minute])
calendar.timeZone = TimeZone(identifier: "UTC")!

let startHour = calendar.component(.hour, from: cell.startDate as Date)
let startMinutes = calendar.component(.minute, from: cell.endDate as Date)

let endHour = calendar.component(.hour, from: cell.endDate as Date)
let endMinute = calendar.component(.minute, from: cell.endDate as Date)

print("start hours = \(startHour) : \(startMinutes)")
print("end hours = \(endHour) : \(endMinute)")

So, the result has been right but in the wrong format. It prints 22:30, for instance, which is what I want, but when it comes to numbers less than 10, like 2 AM for instance, it prints 2:0 instead of 02:00. How can I solve this problem? I am trying to link dateformatter to calendar but I can't. I also tried to solve this by taking the approach below:

let myFormatter = DateFormatter()
myFormatter.dateFormat = "HH:mm"

print(myFormatter.string(from: cell.startDate))
print(myFormatter.string(from: cell.endDate))

But it is printing hours that have nothing to do with the exact hours. Have no idea why.

So, any help would be much appreciated!


There are various ways to add the missing leading zero, however the best solution is using the DateFormatter. You have only one problem with the formatter - setting the correct time zone.

// safer than using identifiers that are not actually standardised
myFormatter.timeZone = TimeZone(secondsFromGMT: 0)