Get weekdays within a month

后端 未结 3 1109
鱼传尺愫
鱼传尺愫 2021-01-03 13:57

I\'m trying to get the dates within a given month.

My plan is to

  1. Get the start and the end dates of a given month,.
  2. Get all the dates that fa
3条回答
  •  情书的邮戳
    2021-01-03 14:26

    With the help of this answer, I was able to accomplish this.

    let calendar = NSCalendar.currentCalendar()
    let normalizedStartDate = calendar.startOfDayForDate(NSDate().startOfMonth)
    let normalizedEndDate = calendar.startOfDayForDate(NSDate().endOfMonth)
    
    var dates = [normalizedStartDate]
    var currentDate = normalizedStartDate
    repeat {
        currentDate = calendar.dateByAddingUnit(NSCalendarUnit.Day, value: 1, toDate: currentDate, options: .MatchNextTime)!
        dates.append(currentDate)
    } while !calendar.isDate(currentDate, inSameDayAsDate: normalizedEndDate)
    
    let weekdays = dates.filter { !calendar.isDateInWeekend($0) }
    weekdays.forEach { date in
        print(NSDateFormatter.localizedStringFromDate(date, dateStyle: .FullStyle, timeStyle: .NoStyle))
    }
    

    And it works!

    Monday, February 1, 2016
    Tuesday, February 2, 2016
    Wednesday, February 3, 2016
    Thursday, February 4, 2016
    Friday, February 5, 2016
    Monday, February 8, 2016
    Tuesday, February 9, 2016
    Wednesday, February 10, 2016
    Thursday, February 11, 2016
    Friday, February 12, 2016
    Monday, February 15, 2016
    Tuesday, February 16, 2016
    Wednesday, February 17, 2016
    Thursday, February 18, 2016
    Friday, February 19, 2016
    Monday, February 22, 2016
    Tuesday, February 23, 2016
    Wednesday, February 24, 2016
    Thursday, February 25, 2016
    Friday, February 26, 2016
    Monday, February 29, 2016
    

提交回复
热议问题