I'm trying to print out the date in a certain format:
NSDate *today = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *dateStr = [dateFormatter stringFromDate:today];
If the iPhone is set to 24 hour time, this works fine, if on the other hand the user has set it to 24 hour time, then back to AM/PM (it works fine until you toggle this setting) then it appends the AM/PM on the end even though I didn't ask for it:
20080927030337 PM
Am I doing something wrong or is this a bug with firmware 2.1?
Edit 1: Made description clearer
Edit 2 workaround: It turns out this is a bug, to fix it I set the AM and PM characters to "":
[dateFormatter setAMSymbol:@""];
[dateFormatter setPMSymbol:@""];
Short answer: try
[dateFormatter setDateFormat:@"yyyyMMddhhmmss"];
for 12 hour format (note the lowercasehh
).It's been a frustrating topic because so many websites indicate to use
HH
for hours (including the official Apple documentation), but that sets it to 24 hour format, whereashh
uses 12 hour format. See http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns for more details.As a bonus, note that you can also use
KK
orkk
for hour of the day format, which will likely be off by one.Update: I was recently looking at NSLocale (https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSLocale_Class/Reference/Reference.html) and it would seem that you can use autoupdatingCurrentLocale to apply changes made from within the app to the Locale. The upshot of this is that even if the phone is set to use a 24 hour clock (like when you switched to France), you can make a 12/24 toggle for the app that won't impact any other apps on the phone, or require you to leave the app to make the change.
Here's the explanation of the iPhone SDK bug (also still there in 3.1 beta SDK)
More details and a possible workaround can be found on this blog.
Setting locale on date formatter to en_US fixes the problem for me:
I'm not sure if adding the calendar is also needed, but this works well.
This should also work (I am seeing some bizzare results though).
Using the code you posted on both the simulator and a phone with the 2.1 firmware and 24-hour time set to off, I never had an AM/PM appended to dateStr when I do:
Are you doing anything else with dateStr that you didn't post here? How are you checking the value?
Follow up
Okay, I see it when I do this also. It's gotta be a bug. I recommend you file a bug report and just check for and filter out the unwanted characters in the meantime.
For those finding this question who want to use NSDateFormatter to parse 24-hour time and are hitting this bug, using NSDateComponents to parse dates and times which have a known format sidesteps this issue: