1

this one is killing me, I have the following date formatter:

+ (NSDateFormatter *)dateFormatter {
    static NSDateFormatter *_dateFormatter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *format = [NSDateFormatter dateFormatFromTemplate:@"hh:mm a" options:0 locale:[NSLocale currentLocale]];
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:format];
    });
    return _dateFormatter;
}   

I want the final hour format to be according to the user clock settings, so if the user uses "24-Hour Time", the result should be for example:

19:41

Otherwise the result should be

7:41 PM

ok now for the "killing me" part, this seems to work great if I set the phone's 'Region Format' to 'United States'.
If I toggle the "24-Hour Time" on/off the date indeed changes from 19:41 to 7:41 PM

BUT if I set the 'Region Format' to something different than 'United States', for example 'Spain' then I always get 7:41 pm no matter if I change the "24-Hour Time" on/off.

Even more weird is the fact that if I use the following template:

@"HH:mm a" (changed hh to uppercase HH)

Now 'Spain' works great and changes according to the "24-Hour Time" settings, BUT now the 'United State' is always in 24 hour format, no matter if I switch it off in settings!

whats going on here?!

Please consider that its important to me to use dateFormatFromTemplate and not regular format.

Eyal
  • 10,777
  • 18
  • 78
  • 130
  • possible duplicate of [What is the best way to deal with the NSDateFormatter locale "feature"?](http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feature) – Hot Licks Apr 01 '14 at 12:10

1 Answers1

0

Try this code

NSDate *time;
if ([objShare checkTimeFormat]){
    [timeFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];;
    [timeFormat setDateFormat:@"hh:mm a"];
    NSLog(@"%@",lblVtime.text);
    time = [timeFormat dateFromString:lblVtime.text];
}
else{
     NSLog(@"%@",lblVtime.text);
    [timeFormat setDateFormat:@"hh:mm a"];
    time = [timeFormat dateFromString:lblVtime.text];
}
[timeFormat setDateFormat:@"HH:mm"];
NSLog(@"%@",[timeFormat stringFromDate:time]);

Let me know if you have any query

The checkTimeFormat method:

-(BOOL)checkTimeFormat{
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     [formatter setLocale:[NSLocale currentLocale]];
     [formatter setDateStyle:NSDateFormatterNoStyle];
     [formatter setTimeStyle:NSDateFormatterShortStyle];
     NSString *dateString = [formatter stringFromDate:[NSDate date]];
     NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
     NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];
     BOOL is24h = (amRange.location == NSNotFound && pmRange.location == NSNotFound);
     return is24h;
}
William Denniss
  • 16,089
  • 7
  • 81
  • 124
kb920
  • 3,039
  • 2
  • 33
  • 44