swift 如果分钟数小于9,则在其前面添加0

ih99xse1  于 2023-01-12  发布在  Swift
关注(0)|答案(2)|浏览(109)

用这个代码你可以保存当前的时间,但是如果分钟数〈9,那么它给你的时间是5:9而不是5:09。2你怎么能修复这个问题呢?

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)"
2g32fytz

2g32fytz1#

你有两个选择。
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.

1.使用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)
bwleehnv

bwleehnv2#

SwiftUi的解决方案:

let date = Date()

Text(date, style: .time) // January 8, 2023
Text(date, style: .date) // 12:08 PM

相关问题