1.NSDate基本概念
NSDate可以用来表示时间, 可以进行一些常见的日期\时间处理
一个NSDate对象就代表一个时间
[NSDate date]返回的就是当前时间
NSDate *now = [NSDate date];
NSLog(@"now = %@", now);
// 设置转换后的目标日期时区
NSTimeZone *zone = [NSTimeZone systemTimeZone];
// 得到源日期与世界标准时间的偏移量
NSInteger interval = [zone secondsFromGMTForDate: date];
NSLog(@"interval = %lu", interval);
// 在当前时间基础上追加时区差值
now = [now dateByAddingTimeInterval:interval];
NSLog(@"%@", date);
2.格式化日期
- NSDate -> NSString
// 1.创建时间
NSDate *now = [NSDate date];
// 2.创建时间格式化
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 3.指定格式
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// 4.格式化时间
NSString *str = [formatter stringFromDate:now];
NSLog(@"%@", str);
- NSString -> NSDate
NSString *str = @"2017-10-25 20:52:05";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *date = [formatter dateFromString:str];
NSLog(@"%@", date);
3.日期时间对象
结合NSCalendar和NSDate能做更多的日期\时间处理
获得NSCalendar对象
NSCalendar *calendar = [NSCalendar currentCalendar];
- 获得年月日
- (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)date;
NSDate *date = [NSDate date];
// 1.创建日历对象
NSCalendar *calendar = [NSCalendar currentCalendar];
// 2.利用日历对象获取年月日时分秒
NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *cmps =[calendar components:type fromDate:date];
NSLog(@"year = %lu", cmps.year);
NSLog(@"month = %lu", cmps.month);
NSLog(@"day = %lu", cmps.day);
NSLog(@"hour = %lu", cmps.hour);
NSLog(@"minute = %lu", cmps.minute);
NSLog(@"second = %lu", cmps.second);
NSLog(@"date = %@", date);
- 比较两个日期的差距
- (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSCalendarOptions)opts;
// 1.确定时间
NSString *time1 = @"2017-10-23 12:18:15";
NSString *time2 = @"2017-10-23 18:10:10";
// 2.将时间转换为date
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *date1 = [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
// 3.创建日历
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
// 4.利用日历对象比较两个时间的差值
NSDateComponents *cmps = [calendar components:type fromDate:date1 toDate:date2 options:0];
// 5.输出结果
NSLog(@"两个时间相差%ld年%ld月%ld日%ld小时%ld分钟%ld秒", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);