1

我想从今天到下个月创建一个 NSDates 数组。这可以很容易地在 Ruby 中使用Time.now..(Time.now + 30.days)

如何像在 Objective C 中的 Ruby 中一样创建日期数组?

4

3 回答 3

5

不幸的是,任何 ObjC 解决方案都将比 Ruby 代码冗长得多。

进行计算的正确方法是NSDateComponents

NSMutableArray * dateArray = [NSMutableArray array];
NSCalendar * cal = [NSCalendar currentCalendar];
NSDateComponents * plusDays = [NSDateComponents new];
NSDate * now = [NSDate date];
for( NSUInteger day = 0; day < NUMDAYS; day++ ){
    [plusDays setDay:day];
    [dateArray addObject:[cal dateByAddingComponents:plusDays toDate:now options:0]];
}

为了使过程更方便(如果您需要执行多次),您可以将此循环放入一个类别方法 on NSCalendarNUMDAYS替换为参数并替换selfcal

于 2013-08-14T21:57:34.990 回答
2

After much downvoting and commenting, here's my REVISED answer...

-(NSDate *)nextDayFromDate:(NSDate *)originalDate {

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [NSDateComponents new];
    dateComponent.day = 1;
    NSDate *tomorrow = [calendar dateByAddingComponents:dateComponent toDate:originalDate options:0];
    return tomorrow;
}

NSMutableArray *dateArray = [NSMutableArray array];
NSDate *now = [NSDate date];
[dateArray addObject:now];
for (int i=0;i<31;i++) {
    NSDate *firstDate = [dateArray objectAtIndex:i];
    NSDate *newDate = [self nextDayFromDate:firstDate];
    [dateArray addObject:newDate];
}

What this does is use the NSCalendar API to add a "day interval" to any given NSDate. Add "Now" to the array, then do a loop 30 times, each time using the previous NSDate object as input to the logic.

于 2013-08-14T21:39:39.887 回答
2

没有什么可以像您发布的 Ruby 一样简洁地做到这一点。分解问题,您需要一种方法来获取特定日期之后的第二天。这是一个可以做到这一点的函数:

NSDate *CalendarDayAfterDate(NSDate *date)
{
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.day = 1;

    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar dateByAddingComponents:components toDate:date options:0];
}

接下来,您需要一个接一个地获取一系列天:

NSDate *today = [NSDate date];
NSMutableArray *dates = [NSMutableArray arrayWithObject:today];
for (NSUInteger i=0; i<30; i++) {
    NSDate *tomorrow = CalendarDayAfterDate(today);
    [dates addObject:tomorrow];
    today = tomorrow;
}
于 2013-08-14T21:57:32.440 回答