get NSString from strftime



我有一个SQLite数据库,它有一个名为start_time的列。当我查询表时,我选择strftime('%H:%M:%S', t1.Time)形式的start_time,并且我可以使用FMDB stringForColumn在一个漂亮的字符串中获得值。但我需要在代码中进行转换(目标C),并且不知道如何进行。该表显示了30、51、25等值。

如何将这些时间值转换为小时和分钟?

非常感谢您的帮助。

我猜您将时间存储为整数(请参阅SQLite"日期和时间数据类型")。您可以使用日期格式化程序(请参阅"日期格式化程序")或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);

最新更新