将月份添加到NewDate

时间:2012-07-11 06:26:04

标签: iphone ipad nsdate nsdateformatter nscalendar

我是iPhone开发人员的新手,

我在该自定义日期中创建了一个custom date我希望根据频率添加1 month3 month6 month

我想添加月份,直到newDate少于今天的日期。

这是我的代码段,

 while ([today compare:temp] == NSOrderedDescending) 
    {        
        NSLog(@"inside----- today=%@,temp=%@",today,temp);

        //add to dates
        NSDateComponents *newComponents= [[NSDateComponents alloc] init];

        if([FrequencySelText isEqualToString:@"Monthly"]){

            [newComponents setMonth:1];
        }
        if([FrequencySelText isEqualToString:@"Quarterly"]){

            [newComponents setMonth:3];
        }
        if([FrequencySelText isEqualToString:@"Half - Yearly"]){

            [newComponents setMonth:6];
        }
        if([FrequencySelText isEqualToString:@"Yearly"]){

            [newComponents setMonth:12];
        }

        // get a new date by adding components
        NSDate* temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0];

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"dd/MM/yyyy"];

        NSString *newDate = [formatter stringFromDate:temp];
        NSLog(@"new date=%@",newDate);
}

我的日志显示: inside----- today=2012-07-11 14:41:27 +0000,temp=2012-04-12 03:00:00 +0000

我在Exc_bad_access

这一行得到NSDate* temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0];

任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:3)

再次为temp提供值,则无需再次提供NSDate对象类型。这里你已经有了NSDate * temp,那么为什么你再次为NSDate对象使用相同的名称

 temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0] 

答案 1 :(得分:0)

也许试试这个:

NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

[dateComponents setMonth:1]; // Sample Add   

NSDate *tempDate = [gregorian dateByAddingComponents:dateComponents toDate: temp options:0];
NSString *strTempDate = [dateFormat stringFromDate:tempDate];

// New Date on strTempDate