首页 > 代码库 > 比较两个NSDate类型的参数相差的时间差
比较两个NSDate类型的参数相差的时间差
+(NSInteger)getDaysFrom:(NSDate *)serverDate To:(NSDate *)endDate
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[gregorian setFirstWeekday:2];
//去掉时分秒信息
NSDate *fromDate;
NSDate *toDate;
[gregorian rangeOfUnit:NSCalendarUnitDay startDate:&fromDate interval:NULL forDate:serverDate];
[gregorian rangeOfUnit:NSCalendarUnitDay startDate:&toDate interval:NULL forDate:endDate];
NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];
return dayComponents.day;
}
//比较选择的开始时间和结束时间的大小
+(BOOL)ComparisonString:(NSString *)str1 andString:(NSString *)str2
{
// NSString *dateStr=@"2015-12-31 01:01:01";//传入时间
//1.获得时间
NSDate *senddate = [ NSDate date ];
NSDateFormatter *dateformatter = [[ NSDateFormatter alloc ] init];
[dateformatter setDateFormat : @"yyyy-MM-dd" ];
NSString *locationString = [dateformatter stringFromDate :senddate];
str2 = locationString;
NSArray *arrya1 = [str1 componentsSeparatedByString:@" " ];
str1 = arrya1.firstObject;
arrya1 = [str2 componentsSeparatedByString:@" " ];
str2 = arrya1.firstObject;
NSString *dateStr = [ NSString stringWithFormat:@"%@ 00:00:01",str1];
//传入时间
//将传入时间转化成需要的格式
NSDateFormatter *format = [[ NSDateFormatter alloc ] init];
[ format setDateFormat:@"yyyy-MM-dd HH:mm:ss" ];
NSDate *fromdate = [format dateFromString:dateStr];
NSTimeZone *fromzone = [ NSTimeZone systemTimeZone ];
NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
NSDate *fromDate = [fromdate dateByAddingTimeInterval: frominterval];
NSLog(@"调的时间=%@",fromDate);
NSString *dateStr1 = [ NSString stringWithFormat : @"%@ 23:59:59",str2];
//传入时间
//将传入时间转化成需要的格式
NSDateFormatter *format1 = [[ NSDateFormatter alloc ] init ];
[format1 setDateFormat : @"yyyy-MM-dd HH:mm:ss" ];
NSDate *fromdate1 = [format1 dateFromString : dateStr1];
NSTimeZone *fromzone1 = [ NSTimeZone systemTimeZone ];
NSInteger frominterval1 = [fromzone1 secondsFromGMTForDate : fromdate1];
NSDate *fromDate1 = [fromdate1 dateByAddingTimeInterval : frominterval1];
NSLog(@"调的时间1=%@",fromDate1);
double intervalTime = [fromDate1 timeIntervalSinceReferenceDate ] - [fromDate timeIntervalSinceReferenceDate ];
long lTime = (long)intervalTime;
NSInteger iDays = lTime/60/60/24;
if (iDays <= 0 ) {
return NO;
}else{
return YES;
}
}
//感谢大神的代码,拷贝为了记录
比较两个NSDate类型的参数相差的时间差