Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

iphone - How to calculate time in hours between two dates in iOS

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 D?r?D?vil's answer below for correctly handling daylight savings/leap seconds


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...