本文介绍了在一个月内获得工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取给定月份内的日期.

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

我的计划是

  1. 获取给定月份的开始日期和结束日期.
  2. 获取该范围内的所有日期.
  3. 使用 isDateInWeekend 方法.

其余日期为工作日.

所以我创建了两个NSDate扩展方法来获取月份的开始日期和结束日期.

So I created two NSDate extension methods to get the start and the end dates of the month.

extension NSDate {
    var startOfMonth: NSDate {
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components([.Year, .Month], fromDate: self)
        return calendar.dateFromComponents(components)!
    }

    var endOfMonth: NSDate {
        let calendar = NSCalendar.currentCalendar()
        let components = NSDateComponents()
        components.month = 1
        return (calendar.dateByAddingComponents(components, toDate: self.startOfMonth, options: NSCalendarOptions())?.dateByAddingTimeInterval(-1))!
    }
}

现在,我陷入了第2步.我找不到找到给定开始日期和结束日期的日期范围的方法.

Now I'm stuck at step #2. I can't find a way to get a range of dates given a start and an end date.

有没有办法做到这一点?

Is there a way to do this?

推荐答案

在此 answer 的帮助下,我能够做到这一点.

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))
}

它有效!

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

这篇关于在一个月内获得工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 15:30
查看更多