我有一个日期选择器。
从中选择一个时间后,我想得到接下来的64个星期一的日期。
我将如何编写一个方法来获取日期并在该日期的下一个64个星期一返回NSArray的NSDr
例如 我从日期选择器下午6:45选择了时间,然后我想在接下来的64个星期一获取,时间设置为那个时间。
答案 0 :(得分:3)
示例(ARC):
NSDate *pickerDate = [NSDate date];
NSLog(@"pickerDate: %@", pickerDate);
NSDateComponents *dateComponents;
NSCalendar *calendar = [NSCalendar currentCalendar];
dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:pickerDate];
NSInteger firstMondayOrdinal = 9 - [dateComponents weekday];
dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:firstMondayOrdinal];
NSDate *firstMondayDate = [calendar dateByAddingComponents:dateComponents toDate:pickerDate options:0];
dateComponents = [[NSDateComponents alloc] init];
[dateComponents setWeek:1];
for (int i=0; i<64; i++) {
[dateComponents setWeek:i];
NSDate *mondayDate = [calendar dateByAddingComponents:dateComponents toDate:firstMondayDate options:0];
NSLog(@"week#: %i, mondayDate: %@", i, mondayDate);
}
NSLog输出:
picker日期:2011-12-09 20:38:25 +0000
周#:0,周日日期:2011-12-12 20:38:25 +0000
周#:1,星期一日期:2011-12-19 20:38:25 +0000
周#:2,周日日期:2011-12-26 20:38:25 +0000
周#:3,星期一日期:2012-01-02 20:38:25 +0000
- 剩下的60岁 -
答案 1 :(得分:2)
从选择器中的NSDate
开始,并继续添加24 * 60 * 60秒,直到它是星期一。将结果日期添加到结果中。继续将7 * 24 * 60 * 60秒添加到您添加的最后一个日期,并将结果推送到返回列表,直到您拥有所有64个星期一。以下是您如何判断NSDate
是否在星期一:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:dateOfInterest];
NSInteger weekday = [weekdayComponents weekday];
if (weekday == 2) ... // 2 represents Monday
编辑:DaveDeLong指出上述算法存在缺陷:在更改为夏令时的时候,它会将时间转移两次。不要手动计算秒数,而是使用此代码将一天添加到NSDate
:
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1]; // Add 1 when searching for the next Monday; add 7 when iterating 63 times
NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate options:0];
[comps release];
答案 2 :(得分:1)
您可以使用NSCalendar来确定今天(在所选时间)的哪一天;将它提升到下一个星期一,然后将它暴露7天63次以获得你想要的星期一。