gpt4 book ai didi

ios - 计算时差iOS

转载 作者:行者123 更新时间:2023-12-01 20:19:49 27 4
gpt4 key购买 nike

我这样写来计算时差。

+ (NSInteger)hoursBetweenDate:(NSDate*)fromDateTime andDate:(NSDate *)toDateTime
{
NSDate *fromDate;
NSDate *toDate;

NSCalendar *calendar = [NSCalendar currentCalendar];

[calendar setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

[calendar rangeOfUnit:NSHourCalendarUnit startDate:&fromDate
interval:NULL forDate:fromDateTime];
[calendar rangeOfUnit:NSHourCalendarUnit startDate:&toDate
interval:NULL forDate:toDateTime];

NSDateComponents *difference = [calendar components:NSHourCalendarUnit
fromDate:fromDate toDate:toDate options:0];

return [difference hour];
}

问题是,如果输入是这样,


2016-03-09 07:58:39 +0000(fromDateTime)
2016-03-09 09:07:44 +0000(toDateTime),


差异总是2小时。实际上,应该是1小时10分钟。结果,我只想显示1小时。有没有办法向上或向下取整?

最佳答案

如果您只是对日期之间的“未格式化”小时数感兴趣,则可以使用NSTimeInterval并轻松进行计算。

+(int)fullHoursBetweenDate:(NSDate *)date1 andDate:(NSDate *)date2 {
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
return (int)interval / 3600;
}

关于ios - 计算时差iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35887470/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com