Get the last time with a period in iPhone 4 with NSDateFormatter

I have a problem with this method:

-(NSString *)getLastTimeMessageWithPeriod:(NSDate*)lastMessageDate { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"h:mm a"]; NSString *resultString = [dateFormatter stringFromDate: lastMessageDate]; return resultString; } 

On iPhone 4 (iOS 7.1), resultString returns “12:32”

On iPhone 5 (iOS 8), resultString returns “12:32 Am”

What could be the problem with missing a period in iPhone 4?

+5
source share
1 answer

I just checked your provided code on my iOS 7.1 device and it gave me “3:22”, so the problem is not with the device or OS version.

The problem is locale, do it like this and it will work

 - (NSString *)getLastTimeMessageWithPeriod:(NSDate *)lastMessageDate { NSDateFormatter *dateFormatter = [NSDateFormatter new]; [dateFormatter setDateFormat:@"h:mm a"]; [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; return [dateFormatter stringFromDate:lastMessageDate];; } 
+1
source

Source: https://habr.com/ru/post/1207801/


All Articles