Get weekdays within a month

后端 未结 3 1107
鱼传尺愫
鱼传尺愫 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:40

    • Get the current calendar

      let calendar = NSCalendar.currentCalendar()
      
    • Get the month and year date components from the current date

      let components = calendar.components([.Year, .Month], fromDate: NSDate())
      
    • Get the date of the first day of the month

      let startOfMonth = calendar.dateFromComponents(components)!
      
    • Get the number of days for the current month

      let numberOfDays = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: startOfMonth).length
      
    • Create an array of NSDate instances for every day in the current month

      let allDays = Array(0..
    • Filter the days within a weekend

      let workDays = allDays.filter{ !calendar.isDateInWeekend($0) }
      

    Swift 3:

    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month], from: Date())
    let startOfMonth = calendar.date(from:components)!
    let numberOfDays = calendar.range(of: .day, in: .month, for: startOfMonth)!.upperBound
    let allDays = Array(0..

提交回复
热议问题