iOS开发中经常遇到时间的转换,这里系统的整理一下。
创建时间对象:
NSDate *currentDate = [NSDate date]; //当前时间
NSDate *earlyDate = [NSDate dateWithTimeIntervalSinceNow:(-24*3600)]; //当前时间之前的一个时间
NSDate *lateDate = [NSDate dateWithTimeIntervalSinceNow:(24*3600)]; //当前时间之后的一个时间
如果想了解时间对象的组成,例如是哪年,这一年的哪个月,这个月的哪天,需要用到NSCalendar和NSDateComponent类
//创建一个日历对象
NSCalendar *calendar = [NSCalendar currentCalendar]; //创建一个日历对象
//创建解析的对象
unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekOfYear;
//创建时间组成对象
NSDateComponents *compents = [calendar components:unitFlags fromDate:date];
//获取年,月,日,小时,分,秒,
NSLog(@"compents.year = %ld\ncompents.month = %ld\ncompents.day = %ld\ncompents.hour = %ld\ncompents.minute = %ld\ncompents.second = %ld",compents.year,compents.month,compents.day,compents.hour,compents.minute,compents.second);
可以通过NSDateComponents对象计算两个时间相差多少年,多少月,多少个小时等。例如可以计算过去一个时间和未来一个时间的差别
NSDateComponents *compents = [calendar components:unitFlags fromDate:earlyDate toDate:lateDate options:0];
NSLog(@"compents.day = %ld",compents.day); // 得到2
NSDate *earlyDate = [NSDate dateWithTimeIntervalSinceNow:(-24*3600*30*12)];
NSDate *lateDate = [NSDate dateWithTimeIntervalSinceNow:(24*3600*30*12)];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitWeekOfYear | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitSecond;
NSDateComponents *compents = [calendar components:unitFlags fromDate:earlyDate toDate:lateDate options:0];
NSLog(@"相差%ld年",compents.year); //相差1年
NSLog(@"相差%ld月",compents.year*12 + compents.month); //相差23月
可通过NSDateComponents方便滴改变时间对象(添加多少天,减少多少天等),例如我们想在当前的时间添加一年。
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:1];
[calendar dateByAddingComponents:components toDate:[NSDate date] options:0];
NSLog(@"components.year = %ld",components.year); // 2015
有时候需要将时间转化成字符串或者数字字符串转换成时间,这可以通过NSDateFormatter 去转换
时间转换成字符串
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = kCFDateFormatterFullStyle;
formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss"; //设置转换后的时间样式
NSString *str = [formatter stringFromDate:[NSDate date]];
NSLog(@"str = %@",str); //2014/11/23 16:46:52
字符串转换成时间
NSString *timeStr = @"14/11/24";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yy/MM/DD";
NSDate *date = [formatter dateFromString:timeStr];