gpt4 book ai didi

objective-c - 创建日期范围

转载 作者:太空狗 更新时间:2023-10-30 03:50:10 25 4
gpt4 key购买 nike

我想创建一个范围数组,其中包含特定开始日期和结束日期之间的天数。

例如,我的开始日期为 2012 年 1 月 1 日,结束日期为 2012 年 1 月 7 日。数组或范围应包含 NSDate 对象的集合(总共 7 个)。

我该怎么做?

最佳答案

NSCalendar 在这里很有用,因为它知道与日期相关的日历。因此,通过使用以下内容(假设您有 startDate 和 endData 并且您希望将两者都包含在列表中),您可以遍历日期,添加一天(NSCalendar 将负责包装月份和闰年等).

NSMutableArray *dateList = [NSMutableArray array];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1];

[dateList addObject: startDate];
NSDate *currentDate = startDate;
// add one the first time through, so that we can use NSOrderedAscending (prevents millisecond infinite loop)
currentDate = [currentCalendar dateByAddingComponents:comps toDate:currentDate options:0];
while ( [endDate compare: currentDate] != NSOrderedAscending) {
[dateList addObject: currentDate];
currentDate = [currentCalendar dateByAddingComponents:comps toDate:currentDate options:0];
}

[comps release];

关于objective-c - 创建日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9651238/

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