vendredi 6 mars 2015

Date from String returns null value

I have the following NSDate 01 Jan 2015 which I want to convert to a string. The string reportArtDate has the string 01 Jan 2015.


My code is:



NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MMM yyyy"];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:reportArtDate];


The above is fine on an iPhone 4, but it fails on an iPhone 5 with version 8.1.3.


But the dateFromString is always null.


Any ideas very welcome.


Thanks a lot.


Edit The problem arises if the users locale is not en_EN. In this case, the user had es_ES locale. So I set the locale before the format set and the NSString was translated to NSDate with success.


The code that works is as follows:



NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]
NSDate *dateFromString = [[NSDate alloc] init];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_EN"]];
[dateFormatter setDateFormat:@"dd MMM yyyy"];
dateFromString = [dateFormatter dateFromString:reportArtDate];


In case it helps others.




Aucun commentaire:

Enregistrer un commentaire