Issues converting DATETIME using SQLITE3 and Objective C

让人想犯罪 __ 提交于 2019-12-02 10:53:17

HH, not hh, is for the 24-hour date format:

[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

Parsing "2013-01-09 16:00:00" with hh as hour-format fails and therefore returns nil.

Note that NSDateFormatter interprets the date string according to the local timezone, unless you set an explicit time zone. You might want to add the time zone information to the strings, or use different format (e.g. UNIX time, seconds since 1.1.1970) to store the date.


ADDED: The SQLite datetime() function returns a string "YYYY-MM-DD HH:MM:SS" which is the date and time in UTC/GMT. To convert such a string to a NSDate, use a NSDateFormatter and set the time zone to GMT:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSString *dateTimeString = @"2013-01-09 16:00:00";
NSLog(@"DateTimeString = %@", dateTimeString);

NSDate *myDate =[dateFormat dateFromString:dateTimeString];
NSLog(@"myDate:          %@", myDate);

Output:

dateTimeString = 2013-01-09 16:00:00
myDate:        = 2013-01-09 16:00:00 +0000

To present a date to the user, convert NSDate to NSString, using stringFromDate, but do not set a time zone (so that the local time zone is used):

NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString *localDateString = [dateFormat2 stringFromDate:myDate];
NSLog(@"localDateString: %@", localDateString);

Output:

localDateString: 2013-01-09 17:00:00

The time is now shown as 17:00:00, because my local time zone is "GMT+01".

The 24-hour format is the only format valid in SQLite date fields.

Please note that the strings in the database are not intended to be directly displayed to the user; modifying them for the user's time zone and formatting preferences is the application's job.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!