Rich
Rich

Reputation: 35

Swift Help to extract a month value from a future date

I'm trying to calculate the month (and year) value from next month's date. I've followed instructions as to how to work out next month's date, but I just need the month value.

I have briefly tried using a DateFormatter, but this was a little over my knowledge about dates.

let calendar = Calendar.current

let rightNow = Date()

let monthOfYear = calendar.component(.month, from: rightNow)

let nextMonthOfYear = calendar.date(byAdding: .month, value: 1, to: rightNow)

If we are in June, I would expect to receive the number of 7 for next month's month value.

Upvotes: 0

Views: 57

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236360

You can get the year and month components from today's date, add one to the month value, create a new date from it and extract its month value:

extension Date {
    var year: Int {
         return Calendar.current.component(.year, from: self)
    }
    var month: Int {
        return Calendar.current.component(.month, from: self)
    }
    var nextMonth: Date {
        return DateComponents(calendar: .current, year: year, month: month+1).date!
    }
}

let now = Date()                     // "28 Jun 2019 17:27"
let nextMonthDate = now.nextMonth    // "1 Jul 2019 00:00"
let nextMonth = nextMonthDate.month  // 7

or simply

Date().nextMonth.month // 7

Upvotes: 2

Related Questions