iosswiftnsdateformatternscalendarnsdatecomponents

NSDateComponents issue when want to get previous month


I have code:

let components = NSDateComponents()
components.month -= 1
let dateInTheMiddleOfPeriod = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))!

But the dateInTheMiddleOfPeriod is 2015-11-18 06:00:12 +0000 , but I expect 2015-12-18 06:00:12 +0000 , because I need the date in the previous month. Why does this happen?


Solution

  • You can use Calendar component method to get the today's Date year and month components, pass day zero and get the month of the resulting date:


    extension Calendar {
        static let iso8601 = Calendar(identifier: .iso8601)
    }
    

    extension Date {
        var year: Int {
            Calendar.iso8601.component(.year, from: self)
        }
        var month: Int {
            Calendar.iso8601.component(.month, from: self)
        }
        var lastDateOfPreviousMonth: Date? {
            DateComponents(calendar: .iso8601, year: year, month: month, day: 0).date
        }
        var previousMonth: Int {
            lastDateOfPreviousMonth?.month ?? 0
        }
    }
    

    Date().lastDateOfPreviousMonth  // "28 Feb 2022 00:00"
    Date().previousMonth            // 2