swift 3 how to get date for tomorrow and yesterday ( take care special case ) new month or new year [duplicate] swift 3 how to get date for tomorrow and yesterday ( take care special case ) new month or new year [duplicate] ios ios

swift 3 how to get date for tomorrow and yesterday ( take care special case ) new month or new year [duplicate]


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   // 10Date().isLastDayOfMonth  // false


I don't know if this helps you or not, but I would recommend not doing the math on NSDateComponents but rather on NSDate. Take a look at https://github.com/malcommac/SwiftDate a cocoapod for how to do things like call tomorrow on an NSDate. The cool thing about that pod is it uses Regions which helps for internationalization where the next day might start at sunset instead of mid nite.