Streetboy
Streetboy

Reputation: 4401

Retrieve Year and Month from string of date

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.

Upvotes: 1

Views: 1293

Answers (2)

jwhat
jwhat

Reputation: 2042

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

Upvotes: 0

Nick Lockwood
Nick Lockwood

Reputation: 40995

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

Upvotes: 2

Related Questions