找到了THIS,但它是针对过去的日期,所以我已根据您的要求为将来的日期更新它。
检查以下示例:
//Future date
let date1 = DateComponents(calendar: .current, year: 2019, month: 3, day: 20, hour: 5, minute: 9).date!
extension Date {
func futureDateDisplay() -> String {
let calendar = Calendar.current
let minutesUntil = calendar.date(byAdding: .minute, value: 1, to: Date())!
let hourUntil = calendar.date(byAdding: .hour, value: 1, to: Date())!
let dayUntil = calendar.date(byAdding: .day, value: 1, to: Date())!
let weekUntil = calendar.date(byAdding: .day, value: 7, to: Date())!
if minutesUntil > self {
let diff = Calendar.current.dateComponents([.second], from: Date(), to: self).second ?? 0
return "\(diff) sec from now on"
} else if hourUntil > self {
let diff = Calendar.current.dateComponents([.minute], from: Date(), to: self).minute ?? 0
return "\(diff) min from now on"
} else if dayUntil > self {
let diff = Calendar.current.dateComponents([.hour], from: Date(), to: self).hour ?? 0
return "\(diff) hrs from now on"
} else if weekUntil > self {
let diff = Calendar.current.dateComponents([.day], from: Date(), to: self).day ?? 0
return "\(diff) days from now on"
}
let diff = Calendar.current.dateComponents([.weekOfYear], from: Date(), to: self).weekOfYear ?? 0
return "\(diff) weeks from now on"
}
}
你可以像这样使用它:
date1.futureDateDisplay() //4 weeks from now on
或者这里是排序解决方案:
let date1 = DateComponents(calendar: .current, year: 2019, month: 3, day: 20, hour: 5, minute: 9).date!
extension Date {
func futureDateDisplay() -> String {
let remainingTime = DateComponentsFormatter()
let calendar = Calendar.current
remainingTime.calendar = calendar
remainingTime.unitsStyle = .full
remainingTime.allowedUnits = [.month,.weekOfMonth, .day, .hour, .minute, .second]
remainingTime.maximumUnitCount = 1
return remainingTime.string(from: Date(), to: self)!
}
}
date1.futureDateDisplay() // 1 month, 1 day