Get an Accurate Time Difference Between two NSDate?

余生颓废 提交于 2019-12-04 18:43:50

问题


Is there any way to find out an accurate difference between two NSDate?

I have found solutions but they aren't accurate enough. I need to take into account daylight saving, the fact that different months have a different number of days, etc.

A simple calculation such as /60/60/24 etc. to work out minutes, hours and days doesn't take them into account.

Lets say I need to work out the difference between the time right now ([NSDate date]) and December 25th 10:22PM (date chosen by user using date picker [datePicker date]) just as an example, how would I do this?
Knowing the exact time difference isn't the key, so long as I have an accurate difference of days, months and years, it will do.


回答1:


From Apple's Date & Time Programming Guide:

Listing 12 Getting the difference between two dates

NSDate *startDate = ...;
NSDate *endDate = ...;

NSCalendar *gregorian = [[NSCalendar alloc]
                 initWithCalendarIdentifier:NSGregorianCalendar];

NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags
                                          fromDate:startDate
                                          toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];



回答2:


NSDate is completely independent of Timezone. Daylight saving doesn't even come into the picture for NSDate. Only when you convert NSDate into a human readable format (MM/DD/YY, HH:MM:SS format or the like), does Time Zone come into picture.

Make sure that you take into account correct timezone, day-light saving setting when you create NSDate(s). Subsequently, the method, [date1 timeIntervalSinceDate:date2] should always give you accurate time difference.




回答3:


So, the more accurate question you meant to ask was: How can I get a nicely formatted days, months, years from a difference between two dates. First you want to get the nsTimerInterval (time difference in seconds) and then format it:

How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?




回答4:


Small update on the code for latest iOS:

NSDate *startDate = ...;
NSDate *endDate = ...;

NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

NSUInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay;

NSDateComponents *components = [gregorian components:unitFlags
                                            fromDate: startDate
                                              toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];


来源:https://stackoverflow.com/questions/8387360/get-an-accurate-time-difference-between-two-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!