转换为NSDate和从NSDate转换会导致崩溃

时间:2013-07-01 12:13:03

标签: objective-c nsstring nsdate

我正在尝试将NSString转换为日期,为其添加一天,然后转换回字符串。

到目前为止,我的代码是:

//convert curDate (from @property declaration) to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:curDate];

//add a day
dateFromString = [dateFromString dateByAddingTimeInterval:60*60*24*1];

//convert back to string (for use in URL string concatenation)
NSString *dateDisplay = [dateFormatter stringFromDate:dateFromString];

//set curDate to new date
curDate = dateDisplay;

它崩溃到了堆栈:

0x117f09b:  movl   8(%edx), %edi

(不确定这是否有用)。

有谁能说这是为什么?

谢谢!

2 个答案:

答案 0 :(得分:2)

您应该使用NSDateComponents

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString =  [dateFormatter dateFromString:self.curDate];

// Create components
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = 1;

// Get the calendar to add the components to a date
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *incrementedDate = [calendar dateByAddingComponents:dateComponents toDate:dateFromString options:0];

NSString *dateDisplay = [dateFormatter stringFromDate:incrementedDate];

//set curDate to new date
curDate = dateDisplay;

答案 1 :(得分:-4)

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"dd-MM-yyyy"];

//add a day

NSDate *dateFromString = [[NSDate date] dateByAddingTimeInterval:60*60*24*1];

//convert back to string (for use in URL string concatenation)

NSString *dateDisplay = [dateFormatter stringFromDate:dateFromString];