作者:晴华姐姐_286 | 来源:互联网 | 2023-02-03 18:16
1> Leo Dabus..:
您应该使用Calendar方法date(byAdding component:)
在中午时间进行日历计算.这样做你不必担心这些特殊情况:
Swift 3或更高版本
extension Date {
static var yesterday: Date { return Date().dayBefore }
static var tomorrow: Date { return Date().dayAfter }
var dayBefore: Date {
return Calendar.current.date(byAdding: .day, value: -1, to: noon)!
}
var dayAfter: Date {
return Calendar.current.date(byAdding: .day, value: 1, to: noon)!
}
var noon: Date {
return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
var month: Int {
return Calendar.current.component(.month, from: self)
}
var isLastDayOfMonth: Bool {
return dayAfter.month != month
}
}
Date.yesterday // "Oct 28, 2018 at 12:00 PM"
Date() // "Oct 29, 2018 at 11:01 AM"
Date.tomorrow // "Oct 30, 2018 at 12:00 PM"
Date.tomorrow.month // 10
Date().isLastDayOfMonth // false
这是一个很好的答案.虽然需要调整.始终存在"今天"或"明天"的背景.所以要么:1.将"今天"和"明天"变量更改为静态2.将变量的名称更改为"dayAfter"和"dayBefore"3.两者.明天和今天保持静止,并将"dayAfter"和"dayBefore"添加为实例变量.我认为这使事情变得更加清晰.