Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
}
like image 834
Ali Avatar asked Apr 05 '26 18:04

Ali


1 Answers

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.

like image 56
RPK Avatar answered Apr 08 '26 19:04

RPK