How to calculate time in hours between two dates in iOS

后端 未结 5 1153
野性不改
野性不改 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:45

    The NSDate function timeIntervalSinceDate: will give you the difference of two dates in seconds.

     NSDate* date1 = someDate;
     NSDate* date2 = someOtherDate;
     NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
     double secondsInAnHour = 3600;
     NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
    

    See, the apple reference library http://developer.apple.com/library/mac/navigation/ or if you are using Xcode just select help/documentation from the menu.

    See: how-to-convert-an-nstimeinterval-seconds-into-minutes

    --edit: See ÐąrέÐέvil's answer below for correctly handling daylight savings/leap seconds

提交回复
热议问题