ios 计算两个时间相差秒数_iOS 比较两个时间的大小,精确到年月日时分秒

本文介绍了在iOS开发中如何精确比较两个日期并计算它们相差的秒数,特别是涉及UTC与本地时间转换的情况。提供了两个方法,一个用于将UTC时间转换为本地时间,另一个用于比较日期是否相差一天,确保精确到秒。对于需要处理时间比较和计算的iOS开发者有参考价值。
摘要由CSDN通过智能技术生成

开发中遇到了要从服务器请求时间,和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

return1;

}else if(hour>-11) {

return0;

}else  if(hour==-11) {

if(min>-35) {

return0;

}else if(min

return1;

}else{

if(second>=0) {

return0;

}else{

return1;

}

}

}else{

return0;

}

}else{

return0;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值