1

I want to retrieve year and then month from this kind of date: 2011-12-23 10:45:01 with no luck.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[dateFormatter setDateFormat:@"yyyy"];
NSLog(@"Date = %@",[dateFormatter dateFromString:@"2011-12-23 10:45:01"]);
[dateFormatter release];

Date = (null), i can't understand why.

Streetboy
  • 4,351
  • 12
  • 56
  • 101

2 Answers2

2

You have to do it in two steps, first match the whole date, then output the bits you want:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:@"2011-12-23 10:45:01"];

//now you have the date, you can output the bits you want

[dateFormatter setDateFormat:@"yyyy"];
NSString *year = [dateFormatter stringFromDate:date];

[dateFormatter setDateFormat:@"MM"];
NSString *month = [dateFormatter stringFromDate:date];

[dateFormatter release];
Nick Lockwood
  • 40,865
  • 11
  • 112
  • 103
0

This was already answered in Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds.

Specifically:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

NSLog(@"\n"
  "theDate: |%@| \n"
  "theTime: |%@| \n"
  , theDate, theTime);

[dateFormat release];
[timeFormat release];
[now release];
Community
  • 1
  • 1
jwhat
  • 2,042
  • 23
  • 29