gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:40:10 32 4
gpt4 key购买 nike

如何获得基于给定日期的月份的实际日期?例如,我想检索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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com