Question

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?

Was it helpful?

Solution

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]

OTHER TIPS

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);
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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top