1.NSDateFormatter配合NSDate与NSString之间的转化NSDateFormatter有下面2个方法:
[Objective-C] 纯文本查看 复制代码 - (NSString *)stringFromDate:(NSDate *)date;//NSDate转NSString
- (NSDate *)dateFromString:(NSString *)string;//NSString转NSDate
e.g.
[Objective-C] 纯文本查看 复制代码 NSString *dateString=@"1900-01-01";
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date=[dateFormatter dateFromString:dateString];
[dateFormatter release];
NSString转NSDate与上面类似
[Objective-C] 纯文本查看 复制代码 NSString *dateString=[dateFormatter dateFromString:[NSDate date]]; 2.NSDateFormatter 的一些格式介绍
[Objective-C] 纯文本查看 复制代码 [dateFormatter setDateFormat:@"yyyy年MM月dd日#EEEE"];//EEEE为星期几,EEE为周几
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setDateFormat:@"yyyy年MMMMd日"];//MMMM 为xx月,一个d可以省去01日前的0 3.NSString转NSDate少一天的解决办法用下面这种格式化方式
[Objective-C] 纯文本查看 复制代码 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];
NSDate *todayDate = [calendar dateFromComponents:components];
|