ios - 如何获得一个月中特定工作日的所有天数?

标签 ios objective-c calendar nscalendar

如何获得基于给定日期的月份的实际日期?例如,我想检索2017年6月的所有日期,即星期六。我该如何实现?样例代码将不胜感激,因为我为此奋斗了几天。

最佳答案

DateComponents具有weekday属性,代表星期几。在基金会的公历中,工作日为1,星期日为2,星期一为…,星期六为7。
DateComponents也具有weekdayOrdinal属性,表示“the position of the weekday within the next larger calendar unit, such as the month. For example, 2 is the weekday ordinal unit for the second Friday of the month.

因此,让我们在2017年6月的某个星期六初始化DateComponents。如果您不在乎时间,通常最好指定中午时间,因为midnight (the default time of day) can cause problems in some time zones on some days

var components = DateComponents(era: 1, year: 2017, month: 06, hour: 12, weekday: 7)

让我们做一个日历。
var calendar = Calendar.autoupdatingCurrent

现在我们可以遍历所有可能的工作日序号。对于每个,我们将要求日历生成一个日期。然后,我们要求日历将日期转换回年,月和日部分。

在公历中,有些月份有5个星期六,但大多数月份有4个星期六。因此,当我们要求第5个星期六时,我们可能会在下个月得到一个日期。发生这种情况时,我们想取消该日期。
for i in 1 ... 5 {
    components.weekdayOrdinal = i
    let date = calendar.date(from: components)!
    let ymd = calendar.dateComponents([.year, .month, .day], from: date)
    guard ymd.month == components.month else { break }
    print("\(ymd.year!)-\(ymd.month!)-\(ymd.day!)")
}

输出:
2017-6-3
2017-6-10
2017-6-17
2017-6-24

Objective-C版本:
NSDateComponents *components = [NSDateComponents new];
components.era = 1;
components.year = 2017;
components.month = 6;
components.hour = 12;
components.weekday = 7;
NSCalendar *calendar = NSCalendar.autoupdatingCurrentCalendar;

for (NSInteger i = 1; i <= 5; ++i) {
    components.weekdayOrdinal = i;
    NSDate *date = [calendar dateFromComponents:components];
    NSDateComponents *ymd = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
    if (ymd.month != components.month) { break; }
    NSLog(@"%ld-%ld-%ld", (long)ymd.year, (long)ymd.month, (long)ymd.day);
}

关于ios - 如何获得一个月中特定工作日的所有天数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44600192/

相关文章:

Objective-C委托(delegate)

android - 如何在日 View 中显示日历

java - 我正在用 java 编写一个日历程序,但除了 2015 年 10 月之外,月份不匹配,我需要帮助

ios - 从 NSData 加载 UIImage 导致不稳定的 UITableView 滚动

ios - Health Kit Statistics Query - 它是否包括来自自己来源的条目?

ios - 我可以在我的 iPhone 上安装由 release(appstore) 配置文件签名的 ipa

objective-c - NSView 或 CALayer 的 subview ?

objective-c - 为从 NSObject 子类化的 Swift 类的实例属性提供自定义后备存储

ios - 比 days/7 更准确地计算自纪元以来的周数

ios - 如何在 Swift 中模仿 safari 的搜索栏 UI/动画?