NSCalendar NSDateComponents
2016-07-07 20:41 xiangjune 阅读(165) 评论(0) 编辑 收藏 举报
// NSCalendar
// 获取当前日历
NSCalendar *calendar = [NSCalendar currentCalendar];
// 获取当前时间日期的各个值
NSDate *currentDate = [NSDate date];
NSUInteger unitFlag = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour |NSCalendarUnitMinute|NSCalendarUnitSecond;
NSDateComponents *com = [calendar components:unitFlag fromDate:currentDate];
NSLog(@"year = %i, month = %i, day = %i, hour = %i, minuts=%i, seconds = %i", com.year, com.month, com.day, com.hour, com.minute, com.second);
// 通过各个值获取NSDate
NSCalendar *calendar1 = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *settingComs = [[NSDateComponents alloc]init];
settingComs.year = 2014;
settingComs.month = 6;
settingComs.day = 1;
settingComs.hour = 11;
settingComs.minute = 30;
settingComs.second = 0;
NSDate *settingDate = [calendar1 dateFromComponents:settingComs];
NSLog(@"settingDate is : %@", settingDate);
// 计算时间差
NSCalendar *diffCalendar = [NSCalendar currentCalendar];
NSString *str1 = @"2016-07-07 20:20:20";
NSString *str2 = @"2016-07-01 10:10:10";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date1 = [dateFormatter dateFromString:str1];
NSDate *date2 = [dateFormatter dateFromString:str2];
NSUInteger diffCalendarUnitFlag = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitSecond;
NSDateComponents *diffComs = [diffCalendar components:diffCalendarUnitFlag fromDate:date1 toDate:date2 options:0];
NSLog(@"year = %i, month = %i, day = %i, hour = %i, minuts=%i, seconds = %i", diffComs.year, diffComs.month, diffComs.day, diffComs.hour, diffComs.minute, diffComs.second);