1

I am in the process of converting a NSString to an NSDate and running into an issue where the year is wrong in the final conversion.

My input date is 2013-05-27 03:38:20 +0000 (listed as lastEntry.date in the code below)

My Conversion code is as follows:

//Convert String to NSDate

NSDateFormatter *originalDateFormat = [[NSDateFormatter alloc] init];

[originalDateFormat setDateFormat:@"YYYY-MM-dd hh:mm:ss Z"];
[originalDateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

NSDate *originalEndDate = [originalDateFormat dateFromString:lastEntry.date];

NSLog(@"Converted End Date = %@", [originalDateFormat stringFromDate:originalEndDate]);

The Final Output I get is: Converted End Date = 2012-05-27 03:38:20 +0000

I am not sure why I am losing a year during this conversion. In all my research so far it seems the hardest part of this conversion process is making sure the format is correct, and since my output date is in the right format I feel there is another issue else where. Is there something that I am missing or doing wrong?

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Sarol
  • 13
  • 1
  • 3
  • Please share the code where you are setting lastEntry.date – Καrτhικ Jan 19 '13 at 18:14
  • 2
    Using big `Y`s as the year may result in not getting back the current calendar year. More here: http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns – Boris Prohaska Jan 19 '13 at 18:23
  • It's probably nothing, but could you post the log output from this: NSLog(@"Converted End Date = %@", originalEndDate); I'd like to see the date without running it through the formatter in both directions. – danh Jan 19 '13 at 18:39
  • @AnoopVaidya and Boris - changing to the yyyy worked great and that link has great information on date formating. Thank you both very much. – Sarol Jan 19 '13 at 18:40
  • possible duplicate of [NSDateFormatter show wrong year](http://stackoverflow.com/questions/12423179/nsdateformatter-show-wrong-year) – vikingosegundo Jan 20 '13 at 17:13

2 Answers2

3

Change your date format from YYYY to yyyy.

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
1

Date formatter Related stuff.

d: 1~31 (0 padded Day of Month) D: 1~366 (0 padded Day of Year)

e: 1~7 (0 padded Day of Week) E~EEE: Sun/Mon/Tue/Wed/Thu/Fri/Sat EEEE: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday

M/MM: 1~12 (0 padded Month) MMM: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec MMMM: January/February/March/April/May/June/July/August/September/October/November/December

y/yyyy: (Full Year) yy/yyy: (2 Digits Year) Y/YYYY: (Full Year, starting from the Sunday of the 1st week of year) YY/YYY: (2 Digits Year, starting from the Sunday of the 1st week of year)

Madhu
  • 1,542
  • 1
  • 14
  • 30