Search code examples
swifttimeseconds

how to avoid one number when the number is 00 in swift 4?


I used the method for current time in my app But the problem is that when the 0 is behind a number the app won't print that like 10:23:4 as you see when the second is 04 the app won't print 04 and print 4 - I know that I can handle this with if else method But I want to know is it possible to fix that in codes or the only way is that? i know that I can use for loop But I want to use one line code to fix that because if use for loop I need to use that for hour and minutes too!

here is my codes

let date = Date()
    let calendar = Calendar.current

    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let seconds = calendar.component(.second, from: date)

    print("Time=\(hour):\(minutes):\(seconds)")

Solution

  • Try this!

    let date = Date()
    let calendar = Calendar.current
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let seconds = calendar.component(.second, from: date)
    let hourString = String.init(format: " %02d:%02d:%02d", hour,minutes,seconds)
    print(hourString)