OnkarK
OnkarK

Reputation: 3793

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.

Upvotes: 3

Views: 81

Answers (2)

Sulthan
Sulthan

Reputation: 130102

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

Upvotes: 4

vadian
vadian

Reputation: 285064

Set the locale of the formatter explicitly to en_US_POSIX

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

Upvotes: 2

Related Questions