I. 获取具体的 年, 月, 日, 时, 分, 秒 元素
//当前日历
NSCalendar *calendar = [NSCalendar currentCalendar];
//获得NSDate每一个元素
// - component:fromDate:
// Desc - Returns the specified date component from a given date
NSInteger year = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:[NSDate date]];
NSInteger day = [calendar component:NSCalendarUnitDay fromDate:[NSDate date]];
QMLog(@"year = %zd month = %zd day = %zd", year, month, day);
//获取NSDate的多个元素
// - components:fromDate:
// Desc - Returns a NSDateComponents object containing a given date decomposed into specified components.
NSDateComponents *cmps = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
QMLog(@"year = %zd month = %zd day = %zd", cmps.year, cmps.month, cmps.day);
II. 比较两个日期之间相差的时间, 可以单独看到每个元素的差值
NSCalendar *calendar = [NSCalendar currentCalendar];
//需要获得的元素枚举
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//相差的时间段
// - components:fromDate:toDate:options:
// Desc: Returns, as an NSDateComponents object using specified components, the difference between two supplied dates.
NSDateComponents *nowCmps = [calendar components:unit fromDate:fromDate toDate:destinationDate options:0];