首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将NSString转换为NSTimeInterval的双倍

将NSString转换为NSTimeInterval的双倍
EN

Stack Overflow用户
提问于 2013-09-03 13:00:39
回答 1查看 3K关注 0票数 1

最终的结果,我需要的是,我想知道多久前,一条评论被张贴。为了做到这一点,我首先做了如下的事情:

代码语言:javascript
运行
复制
double timestampComment = [[testArray objectForKey:@"timestamp"] doubleValue]/1000;
NSDate *date = [NSDate date];
NSLog(@"Date: %@", date);
NSTimeInterval timestamp = (NSTimeInterval)timestampComment;
NSDate *actualTime = [NSDate dateWithTimeInterval:timestamp sinceDate:date];

但这不起作用,并退回了大约5213个月前(这是上周才发布的!)然后我做了一些搜索,发现时间戳的双值,即1377775454768实际上是1377775454768.000000,这就解释了为什么时间是如此的错误。

现在,我尝试了一些控制台日志记录,但仍然无法获得NSTimeInterval没有十进制值的双值。这就是我现在尝试过的:

代码语言:javascript
运行
复制
double timer = [[testArray objectForKey:@"timestamp"]doubleValue];
        //NSString *timerStr = [NSString stringWithFormat:@"%.0f", timer];
        NSString *timerCount = [testArray objectForKey:@"timestamp"];

        NSTimeInterval timeIntervalComment = timer;
        //NSTimeInterval timeIntervalCount = timerCount;
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeIntervalComment];
        NSLog(@"Timer: %@", timerCount);
       NSString *rightTimestr = [NSString stringWithFormat:@"%.0f", timeIntervalComment];
        int timerTest = [rightTimestr intValue];
        NSTimeInterval timeTest = (NSTimeInterval)[timerCount doubleValue];
        NSDate *testDate = [NSDate dateWithTimeIntervalSince1970:timeTest];
        NSLog(@"rightTimestr %@", rightTimestr);
        NSLog(@"timerTest %d", timerTest);
        NSLog(@"%f", [timerCount doubleValue]);
        NSLog(@"Test Date: %@", testDate);
        NSLog(@"Timer 2: %f", timer);
        NSLog(@"date: %@", date);

这是日志记录的结果:

代码语言:javascript
运行
复制
Timer: 1377775454768
rightTimestr 1377775454768
timerTest 2147483647
1377775454768.000000
Test Date: 45629-12-19 04:06:08 +0000
Timer 2: 1377775454768.000000
date: 45629-12-19 04:06:08 +0000

任何帮助都将不胜感激。谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-03 13:05:17

你想知道从现在到发表评论的时间差异。未经测试:

代码语言:javascript
运行
复制
double timestampComment = [[testArray objectForKey:@"timestamp"] doubleValue]/1000;
NSTimeInterval diff = (NSTimeInterval)timestampComment - [[NSDate date] timeIntervalSince1970];

// diff now contains the number of seconds since the comment was posted

但是,您不希望使用NSDate来设置这种差异的格式,因为NSDate用于操作日期,而不是时间增量。您将需要使用这里在Stackoverflow上使用的代码来显示何时发布答案,例如,如果<1小时,然后显示"X分钟前“,否则显示评论发布的日期,等等。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18593020

复制
相关文章

相似问题

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