Yazeed AL-Zahrani
Yazeed AL-Zahrani

Reputation: 87

How to get the date of previous month matching specified day ? [Swift]

How can I get the date of previous month matching specified day ? in Swift

if I have this function getPreviousMonthDate(matchingDay day: Int) -> Date

Examples: following (dd/mm/yyyy)

and so on...

Upvotes: 0

Views: 456

Answers (1)

Asteroid
Asteroid

Reputation: 1118

You can use date components as following:

func getPreviousMonthDate(matchingDay day: Int) -> Date {
    let calendar = Calendar.current
    let comps = calendar.dateComponents([.year, .month, .day], from: Date())
    var comps2 = DateComponents()
    comps2.year = comps.year
    comps2.month = comps.month! - 1
    comps2.day = day
    return calendar.date(from: comps2)!
}

I force-unwrapped the date to match your function declaration, I suggest that you deal with the optional dates properly though.

Upvotes: 1

Related Questions