Travis M.
Travis M.

Reputation: 11257

Date conversion issue with objective C

Weird issue I'm having, if I do this:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM d, yyyy EEEE 'at' h:mm a"];
NSString *originalDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"In Date: %@",originalDate);
NSDate *newDate = [dateFormatter dateFromString:originalDate];
NSLog(@"Out Date: %@",[dateFormatter stringFromDate:newDate]);

I get this output:

In Date: April 30, 2013 Tuesday at 2:42 PM
Out Date: December 28, 1999 Tuesday at 2:42 PM

Why am I getting different dates after converting it to string and back using the same formatter? Is there a way to get this conversion to work properly?

Upvotes: 3

Views: 210

Answers (2)

rmaddy
rmaddy

Reputation: 318774

This is a bug in iOS 6. NSDateFormatter can't properly parse date formats that have the weekday name anywhere besides the start of the string. I submitted a bug report for this a while ago. Still waiting for a fix.

The same format will work under iOS 5.

Update: Based on the test by vikingosegundo I update my own iOS tests. This appears to be the same issues as under OS X. It's not a simple matter of the weekday format being at the start, it is a bug if the weekday format appears after the year format.

Upvotes: 4

vikingosegundo
vikingosegundo

Reputation: 52227

I was able to reproduce this issue in a Cocoa command line program

Working formats

  • @"EEEE MMMM d, yyyy 'at' h:mm a"
  • @"MMMM EEEE d, yyyy 'at' h:mm a"
  • @"MMMM d EEEE, yyyy 'at' h:mm a"

Not working (same symptoms as reported by OP)

  • @"MMMM d, yyyy EEEE 'at' h:mm a"
  • @"MMMM d, yyyy 'at' h:mm a EEEE"

So the EEEE day name specifier needs to be left of the year specifier.
The bug also exists in Cocoa on Mac OS X 10.8.3


for further testing for copy and pasting:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MMMM d, yyyy 'at' h:mm a EEEE"];
        NSString *originalDate = [dateFormatter stringFromDate:[NSDate date]];
        NSLog(@"In Date: %@",originalDate);
        NSDate *newDate = [dateFormatter dateFromString:originalDate];
        NSLog(@"Out Date: %@",[dateFormatter stringFromDate:newDate]);
    }
    return 0;
}

Upvotes: 1

Related Questions