【问题标题】:Accurate timing with NSDateComponents使用 NSDateComponents 精确计时
【发布时间】:2012-06-05 03:41:56
【问题描述】:

我正在尝试建立一个倒计时,它显示要走的秒数。

下例设置为 10 秒,但输出为 8 秒。

NSDate *currentDate = [NSDate date];
NSDate *finishDate = [NSDate dateWithTimeInterval:10 sinceDate:currentDate];

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components = [calendar components:NSSecondCalendarUnit|NSMinuteCalendarUnit|NSHourCalendarUnit | NSDayCalendarUnit| NSMonthCalendarUnit | NSYearCalendarUnit
                                           fromDate:currentDate
                                             toDate:finishDate
                                            options:0];
NSInteger hour_ = [components hour];   
NSInteger minute_ = [components minute];
NSInteger second_ = [components second]; 

日志

currentDate = 2012-06-05 03:13:10 +0000
finishDate_ = 2012-06-05 03:13:19 +0000
second_ = 8

【问题讨论】:

  • 请注意,这并不是真正的“时间”,而是更多的日期计算...

标签: iphone ios nsdate nscalendar


【解决方案1】:

好吧,我刚刚复制并粘贴了您的代码。 我在底部添加了这些行:

NSLog(@"%@", currentDate);
NSLog(@"%@", finishDate);
NSLog(@"%d, %d, %d", hour_, minute_, second_); 

完美运行,在运行 iOS 5.1 的 iPad 模拟器上使用 Xcode 4.3.2:

2012-06-05 00:19:34.341 Testing App[59813:fb03] 2012-06-05 04:19:34 +0000
2012-06-05 00:19:34.342 Testing App[59813:fb03] 2012-06-05 04:19:44 +0000
2012-06-05 00:19:34.343 Testing App[59813:fb03] 0, 0, 10

您是否使用不同的版本?

【讨论】:

  • 我正在使用这些版本。当前和完成日期呢?
  • 现实情况是,这段代码是实际发生的事情的简化版本。我复制了上面的代码并得到了与您相同的结果,因此执行其他导致偏移的任务所花费的时间一定与此有关。
  • 好吧,花额外的时间来计算应该没关系,因为您正在将时间添加到起始值。这是简单的数学......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-27
  • 1970-01-01
相关资源
最近更新 更多