swift 3 how to get date for tomorrow and yesterday ( take care special case ) new month or new year
You should use Calendar method date(byAdding component:)
to do your calendrical calculations using noon time. Doing so you don't need to worry about those special cases:
Swift 3 or Later
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