1

通过我得到的帮助,我已经尝试了很多事情,但我仍然无法弄清楚如何正确地做到这一点。这是我最后所做的。

NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:@"dd-MM-yyy"];

NSDate *currentDate = [NSDate date];
NSDate *fromDate = [NSString stringWithFormat:@"%@",[tempFormatter stringFromDate:currentDate]];
NSLog(@"currentDate %@", fromDate);

NSDate *toDate = [NSString stringWithFormat:@"%@",[tempFormatter stringFromDate:datePicker.date]];
NSLog(@"toDate %@", toDate);

NSTimeInterval interval = [toDate timeIntervalSinceDate:fromDate];
double leftDays = interval/86400;
NSLog(@"Total interval Between::%g",leftDays);

告诉我我做错了什么。是不是 NSDate 转换,我做得不好?谢谢。

4

4 回答 4

2

你的代码都搞砸了——toDate 和 fromDate 都是字符串而不是 NSDates。您的起始日期应该只是 currentDate,而您的 toDate 应该只是 datePicker.date。您无需转换为字符串或使用日期格式化程序来获取时间间隔。

于 2012-11-14T05:33:10.513 回答
2

这条线正在制造问题。

 NSDate *toDate = [NSString stringWithFormat:@"%@",[tempFormatter stringFromDate:datePicker.date]];

它将类型toDate从 NSDate 更改为__NSCFString. 它的NSTimeInterval两个参数都是 NSDate 类型,但在你的情况下只有fromDateNSDate 类型。

使用这些行更改您的代码

NSDate *currentDate = [NSDate date];
    NSDate *toDate = datePicker.date;
NSTimeInterval interval = [toDate timeIntervalSinceDate:currentDate];

它肯定会起作用(inshaAllah)。

于 2012-11-14T05:50:40.387 回答
1

你肯定走在正确的轨道上;但是,您似乎正在使用两个 NSString 调用“timeIntervalSinceDate”(即使您将 fromDate 和 toDate 指定为 NSDates,请在此之后立即查看 - 您正在将这两个变量设置为 NSString 对象)。

要获得您正在寻找的间隔,请尝试:

[datePicker.date timeIntervalSinceDate:currentDate];

这应该让你得到正确的间隔。此外,您可能希望将 leftDays 更改为等于

double leftDays = abs(round(interval/86400));

这将阻止 leftDays 成为像 -1.00005 这样的尴尬数字。

于 2012-11-14T05:34:12.157 回答
1

`将 NSString 传递给 NSDate!这段代码是错误的

尝试

NSDate *curDate = [NSDate Date];
NSDate *pickerDate = datepicker.date;

然后使用 NSTimeInterval 比较这两个日期

于 2012-11-14T05:39:45.903 回答