0

I am trying to parse a date like this: 2012-10-20T13:45:00+002 with this code:

NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate *date = [formatter dateFromString:@"2012-10-20T13:45:00+002"];

But when I try to output it on a device that its timezone is already +2 using this:

NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:@"HH:mm"];
dateformatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"ar_EG"];
cell.infoLabel.text = [dateFormatter stringFromDate:date];

The output is: 15:43 instead of 13:45 as it should be. Any help would be appreciated. PS: I'm running iOS5/6, Xcode 4.5 on iPhone and I tried on both simulator and a physical device.

user1518779
  • 111
  • 5
  • 1
    The ZZZ field is expressed in minutes, not hours. – Hot Licks Oct 11 '12 at 16:03
  • Brilliant! Thank you! This is exactly why! I was also wondering why it displays the date 2 minutes earlier. Can you please tell me what is the correct symbol? I tried reading in http://unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns but I am unsure. – user1518779 Oct 11 '12 at 20:55
  • I believe you will need to append a pair of zeros to the end of the timestamp, to get it to parse correctly. – Hot Licks Oct 12 '12 at 22:31
  • I tried it but it doesn't seem to work: Original string: 2012-11-25T16:00:00+002 After adding the zeros: 2012-11-25T16:00:00+00200 NSLog of the NSDate object: 2012-11-25 15:58:00 +0000 – user1518779 Oct 14 '12 at 12:16
  • It may be that the formatter can't handle the extra leading zero. (But are you sure you're passing the *modified* string to the formatter, and not the original?) – Hot Licks Oct 14 '12 at 12:23
  • (Keep in mind that NSStrings are invariant. When you do, eg, `stringByAppendingString` the original strings are not modified -- you must capture and use the resulting string.) – Hot Licks Oct 15 '12 at 14:43

1 Answers1

0

You need to add locale and timezone

[dateFormatter setLocale:[NSLocale systemLocale]]; // Locale that you want
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; // Timezone the same

S.P.
  • 3,054
  • 1
  • 19
  • 17