iOS NSDate、NSCalendar、NSDateComponents

时间解析(NSDate、NSCalendar、NSDateComponents):

1、使用NSCalendar和NSDateComponents解析日期,直接获取到年月日时分秒。获取到年月日时分秒其实都是通过NSDateComponents来解析的

[calendar components:(NSCalendarUnitYear |NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
NSDate *date = [NSDate date];

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *comps;

    // 年月日获得
 comps = [calendar components:(NSCalendarUnitYear |NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];

NSInteger y = [comps year];

NSInteger m = [comps month];

NSInteger d = [comps day];

NSLog(@"year: %ld month: %ld, day: %ld", y, m, d);

  

//当前的时分秒获得

comps = [calendar components:(NSCalendarUnitHour |NSCalendarUnitMinute | NSCalendarUnitSecond)  fromDate:date];

NSInteger h = [comps hour];

NSInteger m = [comps minute];

NSInteger s = [comps second];

NSLog(@"hour: %li minute: %li second: %li", h, m,s);

  

2、还可以使用NSDateFormatter将日期格式化为 "yyyy-MM-dd hh/HH:mm:ss" 后,再用字符串逐步切割,逐渐获取到年月日时分秒(先用" "切割,然后再用”-“和”:"切割)即可获取到

NSDate *date = [NSDate date];

NSDateFormatter *formatter= [[NSDateFormatteralloc] init];

formatter.dateFormat =@"yyyy-MM-dd HH:mm:ss";

NSString *str = [formatterstringFromDate:date];

 

 NSArray *arr = [str componentsSeparatedByString:@" "];

 NSArray *arr1 = [arr[0] componentsSeparatedByString:@"-"]; // 年 月 日

 NSArray *arr2 = [arr[1] componentsSeparatedByString:@":"]; // 时 分 秒

  

 

posted @ 2016-04-11 20:01  注销这个账号  阅读(754)  评论(0编辑  收藏  举报