如何在几分钟内从日期获取时间,包括“0”?

时间:2018-05-18 08:45:02

标签: swift string time timestamp nsdate

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

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时,当“分钟”低于10小时时,它会给我一些奇怪的值,例如,而不是“9:03”,它将打印“9:3”等。它不包括0在数字之前。使用我当前的方法可以解决这个问题吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

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
}