ios开发--NSDate与NSDateFormatter的相关用法【转】

原文地址:http://blog.sina.com.cn/s/blog_91ff71c0010188u9.html

 

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

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

 
e.g.
 

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

 NSString转NSDate与上面类似

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


2.NSDateFormatter 的一些格式介绍

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

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

 

posted @ 2013-08-14 12:07  归为虚无  阅读(7034)  评论(0编辑  收藏  举报