我有一个 SQLite 数据库,其中有一列名为 start_time。当我查询表时,我选择 strftime('%H:%M:%S', t1.Time)
形式的 start_time 并且我可以使用 FMDB stringForColumn
。但我需要在代码( Objective-C )中进行转换,但不知道如何进行。该表显示了 30、51、25 等值......
如何将这些时间值转换为小时和分钟?
非常感谢任何帮助。
最佳答案
我猜你将时间存储为一个整数(参见 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);
关于ios - 从 strftime 获取 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18476274/