How to calculate time in hours between two dates in iOS

后端 未结 5 1143
野性不改
野性不改 2020-11-29 19:24

How can I calculate the time elapsed in hours between two times (possibly occurring on different days) in iOS?

5条回答
  •  一生所求
    2020-11-29 19:56

    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
    

    Change needed components to day, hour or minute, which difference you want. If NSDayCalendarUnit is selected then it'll return the number of days between two dates similarly for NSHourCalendarUnit and NSMinuteCalendarUnit

    Swift 4 version

    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!
    

提交回复
热议问题