码迷,mamicode.com
首页 > 移动开发 > 详细

iOS NSDate、NSCalendar、NSDateComponents

时间:2016-04-11 20:54:01      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

时间解析(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:@":"]; // 时 分 秒

  

 

iOS NSDate、NSCalendar、NSDateComponents

标签:

原文地址:http://www.cnblogs.com/snowcoming/p/5379928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!