2013-08-27 27 views
1

我有一個名爲start_time的列的SQLite數據庫。當我查詢表格時,我選擇strftime('%H:%M:%S', t1.Time)形式的start_time,並且可以使用FMDB stringForColumn以漂亮的字符串獲取值。但是我需要在代碼中進行轉換(Objective C),並且無法弄清楚。該表顯示的值如30,51,25等,等等......從strftime獲取NSString

如何將這些時間值轉換爲小時和分鐘?

任何幫助,非常感謝。

+0

我可能很密集 - 數據庫中的值是什麼格式,它們是什麼關係?你是否直接存儲字符串? – Tommy

+0

我不確定。不幸的是,當談到SQlite時,我是一個新手。當我使用SQLite Manager查看錶時,類型爲空。 – LittlePeculiar

+0

但是,在那裏的值看起來應該是'%H:%M:%S'或輸入的輸出(不包括:'strftime'執行的語言是什麼?我意識到C調用,但你有單引號作爲字符串分隔符,所以我猜不是)? – Tommy

回答

2

我想你把你的時間存儲爲一個整數(參見SQLite "Date and Time Datatype")。您可以使用日期格式化程序(請參閱"Date Formatters")或unix函數來轉換整數。

使用日期格式:

NSDateFormatter *formatter=[[NSDateFormatter alloc] init]; 
    NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; 
    [formatter setLocale:enUSPOSIXLocale]; 
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 
    [formatter setDateFormat:@"HH:mm:ss"]; 

緩存構建的格式,如果你反覆使用它,然後用它如下:

NSTimeInterval seconds = 465; 

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds]; 
    NSString *dateString = [formatter stringFromDate:date]; 

    NSLog(@"Time is: %@", dateString); 

或者使用UNIX功能:

#include <time.h> 
#include <xlocale.h> 

... 

    time_t seconds = 465; 

    struct tm tm_time; 
    gmtime_r(&seconds, &tm_time); 
    char buffer[9]; 
    strftime_l(buffer, sizeof(buffer), "%H:%M:%S", &tm_time, NULL); 

    NSString *dateString = [NSString stringWithCString:buffer 
               encoding:NSASCIIStringEncoding]; 

    NSLog(@"Time is: %@", dateString);