Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with NSDateFormatter, while NSDate from string with time only

I am facing wired issue with NSDateFormatter.

Following is my code:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mma"];
NSString *currentHours = [formatter stringFromDate:[NSDate date]];
NSLog(@"Hours: %@", currentHours);

If the device setting set to show time in 12 hours (i.e. with AM & PM) following is the output:

Hours: 12:40PM

If the device setting set to show time in 24 hours output is:

Hours: 12:41

This also affecting my other code.

NSDate *open = [formatter dateFromString:@"08:00am"];
NSDate *close = [formatter dateFromString:@"05:00"];

If the device setting set to show time in 24 hours then both date objects are nil. In a case of 12 hours clock setting its working fine.

If any one has solution for same please let me know.

like image 963
OnkarK Avatar asked Mar 08 '26 23:03

OnkarK


2 Answers

Set the formatter locale to:

formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];

However, note that this will force a to English localization "AM"/"PM". Many languages (including mine) don't use a suffix to denote "AM"/"PM".

This is a rather annoying bug but if you care about localization, you should respect user settings and don't force 12h vs 24h time.

Ideally, you should just set the style of the formatter and let it use the system settings:

dateFormatter.dateStyle = NSDateFormatterNoStyle;
dateFormatter.timeStyle = NSDateFormatterShortStyle
like image 136
Sulthan Avatar answered Mar 11 '26 15:03

Sulthan


Set the locale of the formatter explicitly to en_US_POSIX

formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
like image 20
vadian Avatar answered Mar 11 '26 15:03

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!