I’m trying to store today’s date in a sqlite table as a string in a 24-hour time format regardless of the user’s locale. Because NSDate honours the user’s locale, this code returns different results depending on the user’s location:
NSLog(@"The date is %@", [NSDate date]);
If their locale is set to the United Kingdom, where 24-hour time is the default, the above returns
‘The date is 2009-09-05 11:17:35’, whereas if they’re in the United States, where 12-hour time is the default, it returns ‘The date is 2009-09-05 11:17:35 AM’.
Is there a way to automatically detect and convert 12-hour time to 24-hour time before committing it to the database? I’m using SQLite Persistent Objects, so I need to provide the date as an NSDate and not NSString.
In my previous answer I thought you were having issues with SQLite Persistent Objects, but that’s not the case. I think you’ve simply misunderstood what the following code is actually doing:
The reason why you’re getting different log output under different locales is not because of NSDate, it’s because of the NSDateFormatter being used under the hood to insert the string representation of
[NSDate date]into your log string using%@. In fact, NSDate has no concept of “12-hour” or “24-hour” locales — it’s just a representation of a point in time.Locales come into play when you turn your NSDate into a string, such as in an NSLog statement or as part of an SQL query string. When you want to do that, you should specify your own explicit formatter, like so:
Using the above, you should get identical strings regardless of the users’ locale settings.
As for your SQL queries, am I right in thinking that you’re also using
%@to insert the date into the query string? If so, you should do something like this instead:Hope this helps.