0SX*_*0SX 3 iphone macos objective-c nsdate nscalendar
我正在尝试创建一个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);
Run Code Online (Sandbox Code Playgroud)
什么是创建生成器循环日历以从今天的日期开始检索接下来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);
Run Code Online (Sandbox Code Playgroud)
这将创建一个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"
)
Run Code Online (Sandbox Code Playgroud)
需要注意的时区如何抵消了3月13日的变化-0800来-0700.这是夏令时.:)
| 归档时间: |
|
| 查看次数: |
3109 次 |
| 最近记录: |