Sup*_*off 1 nsdate unix-timestamp nstimeinterval ios difference
我正在尝试使用NSTimeInterval来计算我的iOS应用程序中两个时间戳之间的差异.但是,当我尝试传递我的时间戳时,我收到以下错误:
坏接收器类型'双'
这是我的代码:
// Get the current date/time in timestamp format.
NSString *timestamp = [NSString stringWithFormat:@"%f", [[NSDate new] timeIntervalSince1970]];
double current = [timestamp doubleValue];
// Find difference between current timestamp and
// the timestamp returned in the JSON file.
NSTimeInterval difference = [current timeIntervalSinceDate:1296748524];
Run Code Online (Sandbox Code Playgroud)
我认为NSTimeInterval只是双重的另一个含义..不是吗?
请注意,'1296748524'在这里仅用作测试.
我不明白我做错了什么.
谢谢你的时间:)
Log*_*gan 10
我认出那个时间戳!如果你要将时间戳作为字符串,然后将其转换回double,你可以将它作为双精度.
固定:
NSString *timestamp = [NSString stringWithFormat:@"%f", [[NSDate new] timeIntervalSince1970]];
double current = [timestamp doubleValue];
NSTimeInterval difference = [[NSDate dateWithTimeIntervalSince1970:current] timeIntervalSinceDate:[NSDate dateWithTimeIntervalSince1970:1296748524]];
NSLog(@"difference: %f", difference);
Run Code Online (Sandbox Code Playgroud)
更好:
double currentt = [[NSDate new] timeIntervalSince1970];
NSTimeInterval differ= [[NSDate dateWithTimeIntervalSince1970:currentt] timeIntervalSinceDate:[NSDate dateWithTimeIntervalSince1970:1296748524]];
NSLog(@"differ: %f", differ);
Run Code Online (Sandbox Code Playgroud)
但你真正在做的是将日期转换为时间戳到字符串到时间戳到日期到时间戳,所以为什么不从头开始使用它并使用:
最好:
double timeStampFromJSON = 1296748524; // or whatever from your JSON
double dif = [[NSDate date] timeIntervalSince1970] - timeStampFromJSON;
NSLog(@"dif: %f", dif);
Run Code Online (Sandbox Code Playgroud)
一切都会是一样的结果.