【发布时间】:2013-01-13 16:28:09
【问题描述】:
我有一个 sqlite3 数据库,它的 DATETIME 列包含如下格式的值:2013-01-09 04:00:00
我想弄清楚如何确定时间是上午还是下午?
以下是我使用 Objective-C 从我的 Sqlite3 DB 读取和转换 DATETIME 对象的方法:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
char *DateTimeColumn = (char *)sqlite3_column_text(statement, 13);
NSDate *myDate =[dateFormat dateFromString:[NSString stringWithUTF8String:DateTimeColumn]];
这非常有效,只是它无法确定这是凌晨 4:00 还是下午 4:00。
我看到一个帖子建议在格式化程序字符串的末尾添加一个a,如下所示:"yyyy-MM-dd hh:mm:ss a"
...找出上午/下午 - 但这会导致崩溃。 (当然,我还在 DATETIME 列的实际值中添加了 AM 和 PM,如下所示:2013-01-09 04:00:00 AM
但它仍然崩溃了。
不确定我是否做错了什么 - 或者这是否无法完成。
是使数据库本身中的条目全部在 24 小时内的唯一解决方案。格式(意思是:下午 4:00 应该输入为 16:00) - 然后使用IF 语句从 > 12 的值中减去 12 以确定时间的上午或下午?
我原以为会有一些自动化功能……有什么想法吗?
==================================
编辑/更新:
将字符串转换为 NSDate 后,我突然得到一个“(null)”。这是当前版本的代码:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
char *DateTimeColumn = (char *)sqlite3_column_text(statement, 13);
NSString *DateTimeString = [NSString stringWithUTF8String:DateTimeColumn];
NSLog(@"DateTimeString = %@", DateTimeString);
// This NSLog gives me a good string: "DateTimeString = 2013-01-09 16:00:00"
// But when I create an NSDate object from this string:
NSDate *myDate =[dateFormat dateFromString:DateTimeString];
// ... and log it out:
NSLog(@"the REAL DATETIME object = %@", [myDate description]);
// the console shows: "the REAL DATETIME object = (null)"
// and when I add this NSDate object to my Array of NSDates, I crash:
[tempNSDateObjectsArray addObject:myDate];
Console shows:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
*** First throw call stack:
【问题讨论】:
-
嗯,什么崩溃了?这应该不会崩溃,最多返回
nil。大概您的代码中还有其他错误。 -
是的,我只是 NSLogging 一些东西——出于某种原因,我突然得到了一个 NULL 对象。创建我的 NSDate 对象后,我将它添加到一个数组中,我得到了这个:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'我将在顶部编辑问题以获取更多详细信息...
标签: iphone datetime sqlite nsdate