我有一堆
Date
对象,我想要对其执行计算,对于这些计算,我不需要秒精度,因此我尝试将我的 Date
上的秒数“归零”。 这一切都工作正常,除非 Date
已经有零秒,在这种情况下,Swift 将分钟数减一,例如 10:30:00 -> 10:29:00。
我的代码:
let calendar = Calendar.current
var minuteComponent = DateComponents()
minuteComponent.second = 0
let dateDelta = calendar.nextDate(after: date, matching: minuteComponent, matchingPolicy: .nextTime, direction: .backward)
我尝试了所有匹配策略只是得到相同的结果。
这对我来说似乎很奇怪,因为目标已经达到所需的值,尽管我怀疑它与文档一致。
这是将秒归零同时保留较高幅度分量的适当方法还是有更好的方法?
一种选择是使用日期格式化程序,因为这会截断秒数,与向下舍入相同。
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
let noSeconds = formatter.date(from: formatter.string(from: someDate))
这是使用 Calendar 和 DateComponents 的类似解决方案
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: someDate)
let noSeconds = calendar.date(from: components)
用于将秒设置为零的日期扩展...
// Set the Date's seconds to zero.
// This is 'rounding down', the date will be up to 59 seconds earlier than before.
extension Date{
mutating func setSecondsToZero() {
if Calendar.current.component(.second, from: self) != 0 // if seconds are not already zero
{
// set seconds to zero (note, can't do this if seconds are already zero, it will return the minute before.)
if let roundedDate = Calendar.current.nextDate(after: self, matching: DateComponents(second: 0), matchingPolicy: .nextTime, direction: .backward)
{
self = roundedDate
}
}
}
}