如何在 iOS 中计算两个日期之间的小时数
Posted
技术标签:
【中文标题】如何在 iOS 中计算两个日期之间的小时数【英文标题】:How to calculate time in hours between two dates in iOS 【发布时间】:2010-11-03 04:56:56 【问题描述】:如何计算 ios 中两次(可能发生在不同的日子)之间经过的时间(以小时为单位)?
【问题讨论】:
另一种选择是使用NSCalendar
的-components:fromDate:toDate:options:
方法。
我不相信这会给你一个绝对的小时数。它只会给你一个 0-24 的值,你必须依赖组件 Day、Month 和 Year 来获得完整的时间间隔。
我对此进行了测试,它确实工作得很好。使用 fromDate 1/Jan/2012 和 toDate 4/Jan/2012 这返回 96 小时。
张贴您的代码 Thomas?它对某些人不起作用。
【参考方案1】:
NSDate 函数 timeIntervalSinceDate: 将以秒为单位为您提供两个日期的差值。
NSDate* date1 = someDate;
NSDate* date2 = someOtherDate;
NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
看,苹果参考库 http://developer.apple.com/library/mac/navigation/ 或者如果您使用 Xcode,只需从菜单中选择 help/documentation。
见:how-to-convert-an-nstimeinterval-seconds-into-minutes
--edit:见ÐąrέÐέvil's answer below for correctly handling daylight savings/leap seconds
【讨论】:
如果日期/时间跨过夏令时过渡会发生什么? @Abizern:谢谢,当我回答这个问题时,我没有考虑这些情况。我已经链接到 ÐąrέÐέvil 的答案 我有像 4:50:30 这样的时间段,h:m:s 我必须从 12:30:20 中减去这个时间我将如何做到这一点【参考方案2】:NSCalendar *c = [NSCalendar currentCalendar];
NSDate *d1 = [NSDate date];
NSDate *d2 = [NSDate dateWithTimeIntervalSince1970:1340323201];//2012-06-22
NSDateComponents *components = [c components:NSHourCalendarUnit fromDate:d2 toDate:d1 options:0];
NSInteger diff = components.minute;
NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit
将所需的组件更改为您想要的天、小时或分钟。
如果选择了NSDayCalendarUnit
,那么它将返回两个日期之间的天数,同样适用于NSHourCalendarUnit
和NSMinuteCalendarUnit
Swift 4 版本
let cal = Calendar.current
let d1 = Date()
let d2 = Date.init(timeIntervalSince1970: 1524787200) // April 27, 2018 12:00:00 AM
let components = cal.dateComponents([.hour], from: d2, to: d1)
let diff = components.hour!
【讨论】:
dateWithTimeIntervalSince1970 接受什么值?我相信您已将 2012-06-22 日期转换为 1340323201。请纠正我。 不适合我。得到的 diff 值为 9223372036854775807。它以毫秒为单位吗? 斯威夫特 4.2。您可以使用 Set-(NSMutableString*) timeLeftSinceDate: (NSDate *) dateT
NSMutableString *timeLeft = [[NSMutableString alloc]init];
NSDate *today10am =[NSDate date];
NSInteger seconds = [today10am timeIntervalSinceDate:dateT];
NSInteger days = (int) (floor(seconds / (3600 * 24)));
if(days) seconds -= days * 3600 * 24;
NSInteger hours = (int) (floor(seconds / 3600));
if(hours) seconds -= hours * 3600;
NSInteger minutes = (int) (floor(seconds / 60));
if(minutes) seconds -= minutes * 60;
if(days)
[timeLeft appendString:[NSString stringWithFormat:@"%ld Days", (long)days*-1]];
if(hours)
[timeLeft appendString:[NSString stringWithFormat: @"%ld H", (long)hours*-1]];
if(minutes)
[timeLeft appendString: [NSString stringWithFormat: @"%ld M",(long)minutes*-1]];
if(seconds)
[timeLeft appendString:[NSString stringWithFormat: @"%lds", (long)seconds*-1]];
return timeLeft;
【讨论】:
不,不要这样做。并非所有小时都有 3600 秒。并非所有日子都有 24 小时。 这是完全错误的。不考虑闰秒,夏令时节省。请不要重新发明***,只需使用 iOS 提供的 API,例如 NSDateComponents。【参考方案4】:Checkout :它使用 iOS 日历来计算夏令时和闰年。您可以将字符串和条件更改为包括小时和天的分钟。
+(NSString*)remaningTime:(NSDate*)startDate endDate:(NSDate*)endDate
NSDateComponents *components;
NSInteger days;
NSInteger hour;
NSInteger minutes;
NSString *durationString;
components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute
fromDate: startDate toDate: endDate options: 0];
days = [components day];
hour = [components hour];
minutes = [components minute];
if (days > 0)
if (days > 1)
durationString = [NSString stringWithFormat:@"%d days", days];
else
durationString = [NSString stringWithFormat:@"%d day", days];
return durationString;
if (hour > 0)
if (hour > 1)
durationString = [NSString stringWithFormat:@"%d hours", hour];
else
durationString = [NSString stringWithFormat:@"%d hour", hour];
return durationString;
if (minutes > 0)
if (minutes > 1)
durationString = [NSString stringWithFormat:@"%d minutes", minutes];
else
durationString = [NSString stringWithFormat:@"%d minute", minutes];
return durationString;
return @"";
【讨论】:
它没有显示超过 12 小时的差异。如果我想在 23 小时检查某些条件,那么如何获得 23 小时的时间差?【参考方案5】:使用swift 3及以上版本的朋友,
let dateString1 = "2018-03-15T14:20:00.000Z"
let dateString2 = "2018-03-20T14:20:00.000Z"
let Dateformatter = DateFormatter()
Dateformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date1 = Dateformatter.date(from: dateString1)
let date2 = Dateformatter.date(from: dateString2)
let distanceBetweenDates: TimeInterval? = date2?.timeIntervalSince(date1!)
let secondsInAnHour: Double = 3600
let secondsInDays: Double = 86400
let secondsInWeek: Double = 604800
let hoursBetweenDates = Int((distanceBetweenDates! / secondsInAnHour))
let daysBetweenDates = Int((distanceBetweenDates! / secondsInDays))
let weekBetweenDates = Int((distanceBetweenDates! / secondsInWeek))
print(weekBetweenDates,"weeks")//0 weeks
print(daysBetweenDates,"days")//5 days
print(hoursBetweenDates,"hours")//120 hours
【讨论】:
以上是关于如何在 iOS 中计算两个日期之间的小时数的主要内容,如果未能解决你的问题,请参考以下文章