从日期字符串中检索年份和月份

时间:2012-01-24 14:44:54

标签: objective-c ios ios5 nsdate nsdateformatter

我想从这种日期中检索年份和月份:2011-12-23 10:45:01但没有运气。

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

日期=(null),我无法理解为什么。

2 个答案:

答案 0 :(得分:2)

您必须分两步完成,首先匹配整个日期,然后输出您想要的位:

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

答案 1 :(得分:0)

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds已经回答了这个问题。

具体做法是:

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