如果分钟 < 9 在它之前添加一个 0

Dan*_*per 2 date swift

使用此代码,您可以保存当前时间,但如果 Minutes < 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)"
Run Code Online (Sandbox Code Playgroud)

rma*_*ddy 6

你有两个选择。

  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.
    
    Run Code Online (Sandbox Code Playgroud)
  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)
    
    Run Code Online (Sandbox Code Playgroud)