NSDateFormatter用于NSDate与NSString之间的转换:
NSDate转为NSString:
NSDate *date = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; //设置时间输出的格式为年-月-日 时:分:秒 NSString *dateDesc = [dateFormatter stringFromDate:date];
NSString转为NSDate:
NSString *dateDesc = @"2012-11-05"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; //设置时间输出的格式为年-月-日 NSDate *date = [dateFormatter dateFromString:dateDesc];