2
votes

Maybe somebody can help explain why I am getting a null value when converting a string to a date. It all looks right but I'm obviously missing something here.

Some background:

This iPad app will be used in different countries and I will need to do a calculation on the date to see if 90 days have passed since a user last logged in.

I have a SQLite Database with a DateLastIn field set as TEXT

My Object has a DateLastIn property set as NSDate

When populating my record object I set up a NSDateFormatter as such..

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];  // SQLite default date format

Then I read in the DateLastIn (Using FMDB wrapper for SQLite).

        // test SQLite as String
        NSString *testDate = [results stringForColumn:@"DateLastIn"];
        NSLog(@"DateLastIn straight from DB (string) shows %@", testDate);

Result: DateLastIn straight from DB (string) shows 2012-04-23 18:20:51

All is good so far. Next I test converting this to an NSDate object e.g

        NSDate *aDate = [[NSDate alloc] init];
        aDate = [formatter dateFromString:testDate];
        NSLog(@"Using formmater on string date results in: %@", aDate);

Result: Using formmater on string date results in: (null)

I have tried DATETIME in SQLite, I've tried using NSString in my object instead of NSDate and seem to be going around in circles.

Any help much appreciated.

2

2 Answers

4
votes

NSDateFormatter uses the format patterns from the Unicode Technical Standard #35.

For the hour format, you need HH (Hour [0-23]) not hh (Hour [1-12]).

2
votes

I changed your date format to HH not hh and it works. Here is my test code....

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];  // SQLite default date format


// test SQLite as String
NSString *testDate = @"2012-04-23 18:20:51";



NSDate *aDate = [formatter dateFromString:testDate];

NSLog(@"Using formmater on string date results in: %@", aDate);