如何避免数字为00时的一个数字?
我在我的应用程序中使用了当前时间的方法但问题是,当0位于数字后面时,应用程序将不会像10:23:4那样打印,就像您在第二次是04时看到的,应用程序不会打印04和打印4 - 我知道,我可以用其他方法来处理这个问题但是我想知道是否有可能在代码中解决这个问题,或者唯一的方法是?我知道我可以使用for循环但是我想用一行代码来解决这个问题,因为如果使用for循环,我也需要使用它来做小时和分钟!如何避免数字为00时的一个数字?
这里是我的代码
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("Time=\(hour):\(minutes):\(seconds)")
试试这个!
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
let hourString = String.init(format: " %02d:%02d:%02d", hour,minutes,seconds)
print(hourString)
此方法打印此(12:27:0) 所以现在有空间,但仍然没有0 –
我更新了我的答案@SaeedRahmatolahi –
非常感谢这对我工作但请更改打印(“(hourString)”)打印(小时)打印时间 –
请,只是使用DateFormatter https://developer.apple.com/documentation/foundation/dateformatter – Wukerplank
@Wukerplank正好!为什么你不使用DateFormatter? – Fogmeister
我知道Date Formatter是另一种方式但我想知道如何使用这个,你可以在下面看到答案 –