关于这个老问题
从今天的日期减去几周和几天后,我不确定为什么还有一个小时的剩余时间。
dump(Date().xWeeks(-13).xDays(-2).elapsedDescription)
extension Date {
/// Returns a new date that is 'x' number of days hence the recevier.
public func xDays(_ x:Int) -> Date {
return Calendar.current.date(byAdding: .day, value: x, to: self)!
}
/// Returns a new date that is 'x' number of weeks (of year) hence the recevier.
public func xWeeks(_ x:Int) -> Date {
return Calendar.current.date(byAdding: .weekOfYear, value: x, to: self)!
}
/// The count of hours hence the receiver. Today's date is established using the device clock.
public func elapsedHours(toDate: Date) -> Int{
return Calendar.current.dateComponents([.hour], from: self, to: toDate).hour!
}
/// The count of days hence the receiver. Today's date is established using the device clock.
public func elapsedDays(toDate: Date) -> Int{
return Calendar.current.dateComponents([.day], from: self, to: toDate).day!
}
/// The count of weeks hence the receiver. Today's date is established using the device clock.
public func elapsedWeeks(toDate: Date) -> Int{
return Calendar.current.dateComponents([.weekOfYear], from: self, to: toDate).weekOfYear!
}
public var elapsedDescription: String {
let toDate = Date()
let weekValue = elapsedWeeks(toDate: toDate) == 1 ? "week" : "weeks"
if elapsedWeeks(toDate: toDate) > 0 {
let dayRemainder = elapsedDays(toDate: toDate)-elapsedWeeks(toDate: toDate)*7
if dayRemainder > 0 {
let dayValue = dayRemainder == 1 ? "day" : "days"
let remainingHours = elapsedHours(toDate: toDate)-elapsedWeeks(toDate: toDate)*7*24 - (dayRemainder*24)
if remainingHours > 0 {
let hourValue = remainingHours == 1 ? "hour" : "hours"
return "\(elapsedWeeks(toDate: toDate)) \(weekValue), \(dayRemainder) \(dayValue) and \(remainingHours) \(hourValue)"
} else {
return "\(elapsedWeeks(toDate: toDate)) \(weekValue) and \(dayRemainder) \(dayValue)"
}
} else {
return "\(elapsedWeeks(toDate: toDate)) \(weekValue)"
}
} else if elapsedHours(toDate: toDate) > 0 {
let hourValue = elapsedHours(toDate: toDate) == 1 ? "hour" : "hours"
return "\(elapsedHours(toDate: toDate)) \(hourValue)"
} else {
return ""
}
}
}
您的代码假定一天有24小时,但情况并非总是如此。在具有夏令时的区域中,将时钟向前或向后调整时,一天可以有23或25个小时。
在伦敦,夏令时结束于10月30日,这意味着那天有25个小时。这说明了输出中的额外小时。
正确的解决方案很简单:只需一步就可以计算出数周,数天和数小时之间的差异:
let comps = Calendar.current.dateComponents([.weekOfYear, .day, .hour],
from: self, to: toDate)
然后从创建所需的输出字符串
comps.weekOfYear!, comps.day!, comps.hour!
在您的示例中,dump(comps)
显示
▿天:6小时:0 weekOfYear:13 isLeapMonth:false- 天:6- 小时:0 -weekOfYear:13 -isLeapMonth:false
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句