Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last time with 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;
}

In iPhone 4 (iOS 7.1 ) the resultString return " 12:32 "

In iPhone 5 (iOS 8 ) the resultString return " 12:32 Am "

What can be the problem that it makes it miss the period in iPhone 4 ?

like image 293
Roei Nadam Avatar asked Nov 10 '22 22:11

Roei Nadam


1 Answers

I've just tested your provided code on my iOS 7.1 device, and it gave me "3:22", so problem is not device or OS version.

Problem is the locale, do 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];;
}
like image 133
l0gg3r Avatar answered Jan 04 '23 03:01

l0gg3r