我正在尝试创建一个包含夏令时、闰年等的 30 天数组。我目前有一个生成天数数组的生成器,但它没有考虑特殊时间变化和年,月的变化。这是我当前的代码:
NSMutableArray* dates = [[NSMutableArray alloc] init];
int numberOfDays=30;
NSDate *startDate=[NSDate date];
NSDate *tempDate=[startDate copy];
for (int i=0;i<numberOfDays;i++) {
NSLog(@"%@",tempDate.description);
tempDate=[tempDate dateByAddingTimeInterval:(60*60*24)];
[dates addObject:tempDate.description];
}
NSLog(@"%@",dates);
创建生成器以循环遍历日历以检索从今天开始的接下来 30 天的最佳方法是什么,数组应包括今天的日期和接下来的 29 天。我当前的代码就像我说的那样工作,但并不完全准确。谢谢
最佳答案
你快搞定了;只是一些修改:
int numberOfDays=30;
NSDate *startDate=[NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *offset = [[NSDateComponents alloc] init];
NSMutableArray* dates = [NSMutableArray arrayWithObject:startDate];
for (int i = 1; i < numberOfDays; i++) {
[offset setDay:i];
NSDate *nextDay = [calendar dateByAddingComponents:offset toDate:startDate options:0];
[dates addObject:nextDay];
}
[offset release];
NSLog(@"%@",dates);
这将创建一个 NSDate
对象数组。在我的机器上,这个记录:
EmptyFoundation[4302:903] (
"2011-02-16 16:16:26 -0800",
"2011-02-17 16:16:26 -0800",
"2011-02-18 16:16:26 -0800",
"2011-02-19 16:16:26 -0800",
"2011-02-20 16:16:26 -0800",
"2011-02-21 16:16:26 -0800",
"2011-02-22 16:16:26 -0800",
"2011-02-23 16:16:26 -0800",
"2011-02-24 16:16:26 -0800",
"2011-02-25 16:16:26 -0800",
"2011-02-26 16:16:26 -0800",
"2011-02-27 16:16:26 -0800",
"2011-02-28 16:16:26 -0800",
"2011-03-01 16:16:26 -0800",
"2011-03-02 16:16:26 -0800",
"2011-03-03 16:16:26 -0800",
"2011-03-04 16:16:26 -0800",
"2011-03-05 16:16:26 -0800",
"2011-03-06 16:16:26 -0800",
"2011-03-07 16:16:26 -0800",
"2011-03-08 16:16:26 -0800",
"2011-03-09 16:16:26 -0800",
"2011-03-10 16:16:26 -0800",
"2011-03-11 16:16:26 -0800",
"2011-03-12 16:16:26 -0800",
"2011-03-13 16:16:26 -0700",
"2011-03-14 16:16:26 -0700",
"2011-03-15 16:16:26 -0700",
"2011-03-16 16:16:26 -0700",
"2011-03-17 16:16:26 -0700"
)
请注意时区偏移量在 3 月 13 日如何从 -0800
更改为 -0700
。那是夏令时。 :)
关于iphone - 如何使用 NSCalendar 或 NSDate 将 30 天生成为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5023620/