如果分钟是< 9之前加一个0

时间:2017-09-18 15:39:53

标签: swift date

使用此代码,您可以节省当前时间但是如果分钟< 9比它给你5:9而不是5:09的时间。你怎么解决这个问题?

let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let Tijd = "\(hour) : \(minutes)"

1 个答案:

答案 0 :(得分:3)

你有两个选择。

  1. 使用String(format:)

    let date = Date()
    let calendar = Calendar.current
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let tijd = String(format:"%d:%02d", hour, minutes) // change to "%02d:%02d" if you also want the hour to be 2-digits.
    
  2. 使用DateFormatter

    let date = Date()
    let df = DateFormatter()
    df.dateFormat = "H:mm" // Use "HH:mm" if you also what the hour to be 2-digits
    let tijd = df.string(from: date)