首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSDate返回负NSTimeInterval

NSDate返回负NSTimeInterval
EN

Stack Overflow用户
提问于 2014-01-31 19:50:43
回答 2查看 3.7K关注 0票数 2

我有以下代码:

代码语言:javascript
复制
- (void)pointsStartedDisplaying {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            self.timeStartedDisplayingPoint = [NSDate date];
            self.stopButton.enabled = YES;

            [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateElapsedTime:) userInfo:nil repeats:YES];
        });
    });
}

- (void)updateElapsedTime:(NSTimer *)timer {
    NSTimeInterval elapsedTimeDisplayingPoints = [self.timeStartedDisplayingPoint timeIntervalSinceDate:[NSDate date]];
    self.elapsedTimeValueLabel.text = [NSString stringWithFormat:@"%f seconds", elapsedTimeDisplayingPoints];
}

然而,elapsedTimeDisplayingPoints的值是完全准确的,除了每次都是负值。为什么它返回-3, -4, -5,等?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-31 19:53:14

如果接收方早于anotherDate,则返回值为负值。。你的例子就是这样。您可以使用fabs()来获得一个正值。

票数 4
EN

Stack Overflow用户

发布于 2014-01-31 19:53:50

你会得到负数,因为self.timeStartedDisplayingPoint[NSDate date]之前。

你需要:

代码语言:javascript
复制
NSDate *now = [NSDate date];
NSTimeInterval elapsedTimeDisplayingPoints = [now timeIntervalSinceDate:self.timeStartedDisplayingPoint];
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21488817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档