如何从日期中获取时间,包括分钟中的“0”?

How to get time from date including the "0" in Minutes?

我正在使用这种方法在我的应用程序中获取时间:

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

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

let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let year = calendar.component(.year, from: date)

timeStamp = ("\"\(hour):\(minutes)\"")
dateFull = ("\"\(day)/\(month)/\(year)\"")

print(dateFull)
print(timeStamp)

当我打印出 timeStamp 时,当 "Minutes" 低于每小时 10 时,它会给我一些奇怪的值,例如,它将打印“9:3”而不是“9:03”等。它不会t 在数字前包含 0。使用我当前的方法可以解决这个问题吗?

谢谢!

func convertDateToHourMin(date : Date) -> String{
        let calender = Calendar.current
        let components = calender.dateComponents([.hour,.minute,], from: date)
        var hour = String(components.hour!)
        var minute = String(components.minute!)

        if hour.count == 1{
            hour = "0\(hour)"
        }

        if minute.count == 1{
            minute = "0\(minute)"
        }

        return "\(hour)\(minute)"
}

或者你也可以这样写

func convertDateToHourMin(date : Date) -> String{
    let calender = Calendar.current
    let components = calender.dateComponents([.hour,.minute,], from: date)
    let dateInString  = String(format: "%02d:%02d", Int(components.hour!) , Int(components.minute!))
    return dateInString
}