ios - 从 strftime 获取 NSString

标签 ios objective-c sqlite datetime

我有一个 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/

相关文章:

iphone - UIAlertView 单击时崩溃 - 使用 ARC

c# - 包含垃圾字符的 SQLite 文件

ios - 是否可以从 iTunes Connect 下载应用内购买列表?

objective-c - CFUUIDBytes 潜在的 iOS 内存泄漏

ios - WKWebView 需要在 load() 之后延迟设置其 scrollView 的 contentOffset 和 zoomScale

objective-c - 当我尝试在 iOS 6 中运行时,我的代码抛出 Sen 测试框架错误。为什么?

ios - 必须为标识符注册一个 nib 或一个类或连接一个原型(prototype)单元

objective-c - NSNumber 正面回应 mutableCopy?

python - Flask SQLite 查询

R:根据字符向量选择 sqlite 数据库的子集