iOS 判断两个日期之间的间隔

时间:2022-12-06 00:46:18

本文转载至 http://www.cnblogs.com/Ewenblog/p/3891791.html

 

两个时间段,判断之间的相差,做一些时间范围限制使用

    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];

    NSDate* toDate     = [dateFormatter dateFromString:@"20140702142033"];

    NSDate*  startDate    = [ [ NSDate alloc] init ];

    NSCalendar* chineseClendar = [ [ NSCalendar alloc ] initWithCalendarIdentifier:NSGregorianCalendar ];

    NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;

    

    NSDateComponents *cps = [ chineseClendar components:unitFlags fromDate:startDate  toDate:toDate  options:0];

    

    NSInteger diffYear = [cps year];

    NSInteger diffMon = [cps month];

    NSInteger diffDay = [cps day];

    NSInteger diffHour = [cps hour];

    NSInteger diffMin = [cps minute];

    NSInteger diffSec = [cps second];

    NSLog(@" From Now to %@, diff: Years: %d  Months: %d, Days; %d, Hours: %d, Mins:%d, sec:%d", [toDate description], diffYear, diffMon, diffDay, diffHour, diffMin,diffSec );