Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • If Today is 25/07/2022 and I call getPreviousMonthDate(matchingDay: 27)
    : return value would be 27/06/2022 .

  • If Today is 18/04/2022 and I call getPreviousMonthDate(matchingDay: 14)
    : return value would be 14/03/2022 .

  • If Today is 15/01/2022 and I call getPreviousMonthDate(matchingDay: 16)
    : return value would be 16/12/2021 .

and so on…

>Solution :

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
    if comps.month == 1 {
        comps2.year = comps.year! - 1
        comps2.month = 12
    }
    comps2.day = day
    return calendar.date(from: comps2)!
}

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading