NSDate/NSDateFormatter的相关用法

1.NSDateFormatter配合NSDate与NSString之间的转化NSDateFormatter有下面2个方法:

1
2
- (NSString *)stringFromDate:(NSDate *)date;//NSDate转NSString
- (NSDate *)dateFromString:(NSString *)string;//NSString转NSDate

e.g.

1
2
3
4
5
NSString *dateString=@"1900-01-01";
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date=[dateFormatter dateFromString:dateString];
[dateFormatter release];

NSString转NSDate与上面类似

1
NSString *dateString=[dateFormatter dateFromString:[NSDate date]];

2.NSDateFormatter 的一些格式介绍

1
2
3
[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少一天的解决办法用下面这种格式化方式

1
2
3
4
5
[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];

Leave a Reply