0

How do I convert "4:15:00 PM" to an NSDate? Below is the code I have:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"HH:mm:ss aa"];
NSDate *date =  [df dateFromString:@"4:15:00 PM"];

NSLog(@"date: %@",date);//outputs: 1970-01-01 17:15:00 +0000
//should output: 1970-01-01 16:15:00 +0000

UPDATE: I updated based on responses and I am still having the incorrect show:

NSLog(@"date: %@",[df stringFromDate:date]);//outputs: 12:15:00 PM
//should output: 4:15:00 PM

The question is why does the time change from 4:15:00 PM 12:15:00 PM.

joe
  • 16,988
  • 36
  • 94
  • 131

2 Answers2

5

Actually, this is correct.

However, the debugger and NSLog display the time in GMT.

If you want to display local time, use a NSDateFormatter and stringFromDate.

Update:
Your date formatter format is also set incorrectly.

It should be: [df setDateFormat:@"hh:mm:ss aa"]; since you are using a 12 hour clock.

lnafziger
  • 25,760
  • 8
  • 60
  • 101
  • Umm, it is outputting the correct time now. Just change the format if you want it to display differently. – lnafziger May 30 '12 at 17:11
2

This is because of your locale.

NSDateFormatter outputs a NSDate - which is always in GMT time.

If you want your initial string interpreted as GMT time then you need to include the timezone.

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"HH:mm:ss aa z"];
NSDate *date =  [df dateFromString:@"4:15:00 PM GMT"];
trapper
  • 11,716
  • 7
  • 38
  • 82
  • Can I do this without having to change to append GMT to the input string? – joe May 30 '12 at 17:09
  • If you don't put GMT then it is going to use your locale's timezone – trapper May 30 '12 at 17:19
  • If its defaulting then why do I have the issue where the time changes from "4:15:00 PM" to "12:15:00 PM" – joe May 30 '12 at 17:23
  • Those are the same raw NSDate. It *looks* like it is changing because '4:15:00 PM', unless otherwise stated, is assumed to be in your current locales timezone. Where as NSDate is always stored in GMT time, so it does a timezone conversion *to* GMT time when you use `dateFromString`. – trapper May 31 '12 at 08:49