iOS 比较两个时间的大小,精确到年月日时分秒

开发中遇到了要从服务器请求时间,和model里的时间比较,刚开始就是拿着系统方法直接比较发现,不能精确到秒,要求是过完凌晨12点算一天。俩个时间必须统一格式,否则,判断不出。时间又分为国际时间和本地时间只说,真是不用不知道,一用发现还有很多区别,所以写下这篇文章,供以后查阅。

时间格式:@"2017-09-27 11:30:15"entity.PublishTime

俩个时间要统一格式,后面的判断可以根据自己的需求改动,我这里要精确到相差到11小时35分,判断写的很垃圾,但是能看懂。

//国际UTC转本地时间

- (NSDate*)getNowDateFromatAnDate:(NSDate*)anyDate {

//设置源日期时区

NSTimeZone* sourceTimeZone = [NSTimeZonetimeZoneWithAbbreviation:@"UTC"];//或GMT

//设置转换后的目标日期时区

NSTimeZone* destinationTimeZone = [NSTimeZonelocalTimeZone];

//得到源日期与世界标准时间的偏移量

NSIntegersourceGMTOffset = [sourceTimeZonesecondsFromGMTForDate:anyDate];

//目标日期与本地时区的偏移量

NSIntegerdestinationGMTOffset = [destinationTimeZonesecondsFromGMTForDate:anyDate];

//得到时间偏移量的差值

NSTimeIntervalinterval = destinationGMTOffset - sourceGMTOffset;

//转为现在时间

NSDate* destinationDateNow = [[NSDatealloc]initWithTimeInterval:intervalsinceDate:anyDate];

returndestinationDateNow;

}

//比较两时间的前后

- (int)compareOneDay:(NSDate*)oneDay withAnotherDay:(NSDate*)anotherDay{

NSCalendar*gregorian =[[NSCalendaralloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

unsignedintunitFlags=NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|kCFCalendarUnitHour|kCFCalendarUnitMinute|kCFCalendarUnitSecond;

NSDateComponents*comps=[gregoriancomponents:unitFlagsfromDate:oneDaytoDate:anotherDayoptions:0];

NSIntegeryear= [compsyear];

NSIntegermonth = [compsmonth];

NSIntegerday= [compsday];

NSIntegerhour= [compshour];

NSIntegermin= [compsminute];

NSIntegersecond = [compssecond];

if(year>0) {

    return0;

}

if(month>0&&year<=0) {

       return0;

}

if(month<=0&&year<=0&&day>0) {

       return0;

}

if(day<=0||month<=0||year<=0) {

     if(day<0||month<0||year<0) {

                 return1;

}

if(hour<-11) {

       return1;

}else if(hour>-11) {

       return0;

}else  if(hour==-11) {

if(min>-35) {

    return0;

}else if(min<-35){

    return1;

}else{

if(second>=0) {

   return0;

}else{

   return1;

}

}

}else{

   return0;

}

}else{

    return0;

}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容