将UIEvent时间戳转换为UNIX日期



我使用类似的touchbegin函数

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
{
  touchStartTime = [event timestamp];
  NSLog(@"Time of touch is %f ", touchStartTime);
}

但我想把它和比较一下

double timeToCompare = [[NSDate date] timeIntervalSince1970];

但是格式不兼容(时间戳具有一些其他参考点)。如何将[event timestamp]转换为正常的NSDate,反之亦然?

由于[事件时间戳]与系统运行时间有关,您可以同时获得[NSProcessInfo systemUptime]和当前系统时间,然后从那里开始。

[[NSDate date] timeIntervalSince1970] - [NSProcessInfo systemUptime] + [event timestamp] == [compareDate timeIntervalSince1970]

(嗯,我没有用血签这个。我自己从来没有试过。)

假设[UIEvent timestamp]是自系统启动以来的秒数,一种方法是记录第一个事件的时间戳并将其用作参考。

@interface MyClass ()
{
    BOOL _haveFirstTimestamp;
    NSTimeInterval _firstTimestamp;
    NSTimeInterval _firstTimestampTime;
}
@end
...
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
{
    NSTimeInterval timestamp = [event timestamp];
    if (!_haveFirstTimestamp) {
        _haveFirstTimestamp = YES;
        _firstTimestamp = timestamp;
        _firstTimestampTime  = [[NSDate date] timeIntervalSince1970];
    }
    NSTimestamp timeSince1970 = timestamp - _firstTimestamp + _firstTimestampTime;
    NSLog(@"Time of touch is %f ", timeSince1970);
}

最新更新