【问题标题】:Days Difference between current and an up coming Date in iOSiOS 中当前日期和即将到来的日期之间的天数差异
【发布时间】:2012-11-14 05:16:00
【问题描述】:

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

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 转换,我做得不好? 谢谢。

【问题讨论】:

    标签: iphone objective-c xcode ios5


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      此行存在问题。

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

      它将 toDate 的类型从 NSDate 更改为 __NSCFStringNSTimeInterval 采用 NSDate 类型的两个参数,但在您的情况下,只有 fromDate 是 NSDate 类型。

      用这些行改变你的代码

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

      它肯定会起作用(inshaAllah)。

      【讨论】:

        【解决方案3】:

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

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

        [datePicker.date timeIntervalSinceDate:currentDate];
        

        这应该可以为您提供正确的间隔。此外,您可能希望将 leftDays 更改为等于

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

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

        【讨论】:

          【解决方案4】:

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

          试试

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-04-23
            • 1970-01-01
            • 1970-01-01
            • 2016-06-22
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多