2012-05-15 63 views
2

我試圖將時間戳(NSTimeInterval)轉換爲日期格式。我得到正確的當前日期(日 - 月 - 年),但時間不對。這是我的代碼。我如何解決它以正確獲取當前時間?提前致謝。將時間戳轉換爲日期格式

- (NSString*)formatTimestamp:(NSTimeInterval)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; 
} 
+0

您需要更多地解釋「時間不對」。怎麼了?你想要發生什麼? –

+0

時間不是當前時間。例如,NSLog的時間是2012-05-15 15:27:26.505,但這是我從我的代碼中得到的:15-05-2012 22:01:15:856 PDT。我想獲得與NSLog的時間戳相同的時間。 – HappyAppDeveloper

+0

您使用NSLog打印哪個變量?您是否使用NSLog打印「日期」以及方法的返回值? –

回答

3

也許我誤解的東西,但我覺得你的比較是不正確的......

NSLog的時間是當前時間UIEventtimestamp因爲系統啓動的秒數(和你它添加到當前的時間[NSDate dateWithTimeIntervalSinceNow:])...

如果你想你需要先得到系統的啓動日期,這是不那麼容易......一個UIEvent的絕對日期時間,然後添加UIEventtimestamp

您可以使用

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

+0

感謝您的解釋。你是絕對正確的。我誤解了UIEvent的時間戳,這實際上是系統啓動後的秒數。你的解決方案運行良好,但我可以從這裏得到「secondsSinceLastReboot」:NSTimeInterval secondsSinceStartup = [[NSProcessInfo processInfo] systemUptime]; – HappyAppDeveloper

+0

感謝您的提示,我不知道這個功能(僅適用於iOS4 +)。 –

1

您是否需要設置時區?

NSTimeZone * timeZone = [NSTimeZone timeZoneWithName:@「YourTimeZone」]; [foprmatter setTimeZone:timeZone];

+0

是的,我沒有嘗試[格式化setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@「PDT」]] ;然而,時間看起來不正確。例如,NSLog的時間是2012-05-15 15:27:26.505,這是我從代碼中得到的結果:15-05-2012 22:01:15:856 PDT。 – HappyAppDeveloper