-5

The code I've used is working, but I have a problem. For example, when the minute is 02, it says 2. I want it to be 02.

@objc func tick() {
        var calendar = Calendar(identifier: .iso8601)
        calendar.timeZone = NSTimeZone.local
        let currentDay = calendar.component(.day, from: Date())
        let currentMonth = calendar.component(.month, from: Date())
        let currentYear = calendar.component(.year, from: Date())
        let currentHour = calendar.component(.hour, from: Date())
        let currentHour1 = calendar.component(.minute, from: Date())

        labelTimer.text = String (currentDay) + ("/") + String (currentMonth) + ("/") + String (currentYear) + ("/") +  String (currentHour) + (":") + String (currentHour1)    
    }
Dezso Gabos
  • 2,297
  • 5
  • 21
  • 29

1 Answers1

2

The solution to your problem is using a date formatter like so:

let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy/HH:mm"

@objc func tick() {

    labelTimer.text = formatter.string(from: Date())

}

Note: You can simply change the string the way you want and obtain another date string. For example setting "dd-MM-yyyy hour:HH minute:mm" would work as well

marc
  • 914
  • 6
  • 18