OGeek|极客世界-中国程序员成长平台

标题: iphone - 将时间戳转换为日期格式 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 20:59
标题: iphone - 将时间戳转换为日期格式

我正在尝试将时间戳 (NSTimeInterval) 转换为日期格式。我得到了正确的当前日期(日-月-年),但时间不对。这是我的代码。如何修复它以正确获取当前时间?提前致谢。

- (NSString*)formatTimestampNSTimeInterval)timeStamp
{
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:timeStamp];
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat"dd-MM-yyyy HH:mm:ss:SSS zzz"];
    NSString *dateString=[formatter stringFromDate:date];
    [formatter release];
    return dateString;
}



Best Answer-推荐答案


也许我误解了一些东西,但我认为你的比较不正确......

NSLog的时间是当前时间UIEventtimestamp的个数系统启动后的秒数(然后您使用 [NSDate dateWithTimeIntervalSinceNow:] 将其添加到当前时间)...

如果你想要一个UIEvent的绝对日期时间,你需要先获取系统启动日期,这并不容易……然后添加UIEvent >时间戳.

你可以使用

lastRebootTime = [[NSDate date] addTimeInterval:-[self secondsSinceLastReboot]];

- (NSTimeInterval)secondsSinceLastReboot
{
    // get the timebase info -- different on phone and OSX
    mach_timebase_info_data_t info;
    mach_timebase_info(&info);

    // get the time
    uint64_t absTime = mach_absolute_time();

    // apply the timebase info
    absTime *= info.numer;
    absTime /= info.denom;

    // convert nanoseconds into seconds
    return (NSTimeInterval) ((double)absTime / 1000000000.0);
}

参照。 Generating iPhone UIEvent Timestamps

关于iphone - 将时间戳转换为日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10609474/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4