I have written a simple function to return the NSDate from an NSString. But it is always returning 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];
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With