CarlJ
CarlJ

Reputation: 9481

NSString to NSDate dont work on iDevice

i have a problem to convert a NSString to a NSDate and back to a formatted NSString. The codesnippet works without any problem on the iOS Simulator but doesnt work on my iPhone 4.

NSString *pubDate = @"Tue, 18 Oct 2011 05:00:00 +0100";

NSDateFormatter *formater1 = [[NSDateFormatter alloc] init];
[formater1 setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];

NSDate *d = [formater1 dateFromString:pubDate];
NSLog(@"d: %@", d);


NSDateFormatter *formater2 = [[NSDateFormatter alloc] init];
[formater2 setDateFormat:@"dd MMM yyyy"];

NSString *k = [formater2 stringFromDate:d]; 
NSLog(@"k: %@", k);

[formater1 release];
[formater2 release];

The output from the simulator is:

d: 2011-10-18 04:00:00 +0000
k: 18 Oct 2011

The output on the device is:

d: (null)
k: (null)

Any suggestions?

Upvotes: 1

Views: 138

Answers (2)

hypercrypt
hypercrypt

Reputation: 15376

You need to set a locale on the date formatters.

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

//...
formater1.locale = locale;

//...
formater2.locale = locale;

//...
[locale release];

If you don't set the locale then user's settings can change the provided string to conform with user's setting, such as change 12h to 24h clock or vice versa.

Upvotes: 2

rckoenes
rckoenes

Reputation: 69499

This could be because the device is not set to english, thus it can't parse the Tue and Oct in the pubDat.

Try adding a an locale to the NSDateFormatter:

[formater1 setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"EN"] autorelease]];

Upvotes: 0

Related Questions