Reputation: 892
I have a NSDate that I want to display in 4:00 PM form.
NSDate *time = [object objectForKey:@"time"];
NSLog(@"time: %@", time);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [NSLocale currentLocale];
[dateFormatter setDateFormat:@"h:mm a"];
timeLabel.text = [dateFormatter stringFromDate:time];
The log returns:
2014-03-08 13:00:00 +0000
But timeLabel.text reads 1:00 AM, when it should be pm. Any idea what's going on?
Upvotes: 0
Views: 178
Reputation: 50089
You forgot to add the timezone. The rest is fine. You have to give the formatter a timezone or it will use your local one
also be aware that logging with NSLog ALWAYS prints UTC dates
use [formatter setTimezone:timeZoneXY]
Upvotes: 4
Reputation: 23271
NSDate *time = [object objectForKey:@"time"];
NSLog(@"time: %@", time);
Your time variable time format is have 24 hour format. that way it display NSLog 13.00.
After that you have use to converter 12 hour format thats way it display am/pm style
[dateFormatter setDateFormat:@"h:mm a"];
Note:
HH - captial letter H is denote 24 hour format
hh - small letter h is denote 12 hour format
Upvotes: 0
Reputation: 425
you can use following code:
NSString *str=@"17-02-2014 05:00 PM";
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm a"];
NSDate *datetoday=[dateFormatter dateFromString:str];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSString *strdate=[dateFormatter stringFromDate:datetoday];
NSLog(@"%@",strdate);
Upvotes: 0