Foundation框架-06 日期类NSDate和日历类NSCalendar
1.NSDate基本概念
- NSDate基本概念
- NSDate可以用来表示时间,可以进行一些常见的日期\时间处理
- 一个NSDate对象就代表一个时间
- [NSDate date]返回的就是当前时间
NSDate *now = [NSDate date];
NSLog(@"now = %@", now);
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: now];
NSLog(@"interval = %lu", interval);
now = [now dateByAddingTimeInterval:interval];
NSDate *now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy年MM月dd日 HH时mm分ss秒 Z";
NSString *res = [formatter stringFromDate:now];
NSLog(@"res = %@", res);
NSString *str = @"2015-06-29 07:05:26 +0000";
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
NSDate *date = [fomatter dateFromString:str];
2.NSDate与NSCalendar日历类
- 结合NSCalendar(日历类)和NSDate做时间的处理
NSDate *now = [NSDate date];
NSCalendar *calendar1 = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear |
NSCalendarUnitMonth |
NSCalendarUnitDay |
NSCalendarUnitHour |
NSCalendarUnitMinute |
NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar1 components:type fromDate:now];
NSLog(@"year = %ld", cmps.year);
// 过去的一个时间
NSString *str = @"2015-06-29 07:05:26 +0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
NSDate *date = [formatter dateFromString:str];
// 当前的时间
NSDate *now = [NSDate date];
// 比较两个时间
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear |
NSCalendarUnitMonth |
NSCalendarUnitDay |
NSCalendarUnitHour |
NSCalendarUnitMinute |
NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar components:type fromDate:date toDate:now options:0];
NSLog(@"%ld年%ld月%ld日%ld小时%ld分钟%ld秒钟", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);