2017-09-18 34 views
1

用這段代碼你可以保存當前的時間,但是如果分鐘數爲< 9比它給你5:9而不是5:09的時間。你怎麼解決這個問題?如果分鐘數<9,在它之前加一個0

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

使用日期格式化器與適當配置的日期格式。不要自己寫這個日期到字符串轉換。與大多數人不一樣的日期/時間。你不能忘記國際化。 – Alexander

+2

[Swift數字格式化]的可能的重複(https://stackoverflow.com/questions/26167453/swift-number-formatting) –

+1

我引用的問題顯示瞭如何獲得字符串以打印出前導零或接受一定的空間。 –

回答

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) 
    
+1

DateFormatter FTW –

相關問題