比较两个NSDate类型的参数相差的时间差
Posted 超越ME
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了比较两个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 *[email protected]"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类型的参数相差的时间差的主要内容,如果未能解决你的问题,请参考以下文章
iOS-获取的NSDate date时间与实际相差8个小时解决方案