Search code examples
iphoneiosobjective-cnsdatensdateformatter

NSDateFormatter, am I doing something wrong or is this a bug?


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:@""];

Solution

  • 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:

    NSLog(@"%@", dateStr);
    

    Are you doing anything else with dateStr that you didn't post here? How are you checking the value?

    Follow up

    Try turning the am/pm setting on then off. I didn't have the problem either, until I did that. I am printing it out the same way you are.

    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.