Ali Zahr Ali Zahr - 3 months ago 48
iOS Question

NSDate dateFromString returns nil on Device Language Change

I have written a simple function to return the NSDate from an NSString. But it is always returning nil.

The scenario is:




  1. The device language is English, the function works fine.

  2. The device language is Arabic, the functions returns nil.



The NSString value is "03:43 PM". However if the date is formatted in arabic i.e "٠٩:٥٦ ص". It returns a correct date. Any idea?

Code:

- (NSDate*) GetTime:(NSString*) txt
{
NSDateFormatter *df=[[NSDateFormatter alloc] init];
[df setDateFormat:@"hh:mm a"];

return [df dateFromString:txt];
}

RPK RPK
Answer

Going by the comments above, set the locale as follows

- (NSDate*) GetTime:(NSString*) txt
{
    NSDateFormatter *df=[[NSDateFormatter alloc] init];
    [df setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]];
    [df setDateFormat:@"hh:mm a"];

    return [df dateFromString:txt];
}

This will ensure that no matter the devices locale, if you are passing it an english string for the time in the required format, it will properly create an NSDate.