Search code examples
swiftdatensdatensdateformatternsdatecomponents

How can i print the dates of the first five month of a given year in the format below


I want to print the dates of the first 5 months in a given year with the formats below.

2019-05, 2019-04, 2019-03, 2019-02, 2019-01

Im using a for loop to achieve this

    var  first5monthIn2019 : [String]{
    var dates : [String] = []
    for i in 01...05 {
        dates.append("2019-0\(i)")
    }
      return dates
    }

Is there any accepted approach using NSdate to achieve the above.


Solution

  • Here is a simple solution with DateComponents

    for month in 1...5 {
        if let date = DateComponents(calendar: Calendar.current, year: 2019, month: month, day: 1).date {
            print(date)
        }
    }