0

I'm trying to perform date calculations for a scheduling app but am running into issues with daylight savings time. I'm trying to determine the number of days between two dates with:

NSDateComponents *activityComponents = [[NSDateComponents alloc]init];
activityComponents = [self.calendar components:NSDayCalendarUnit
                                      fromDate:self.viewBeginDate
                                        toDate:item.ES
                                       options:0];
NSLog(@"Days: %d and hours: %d", [activityComponents day], [activityComponents hour]);

where self.viewBeginDate and item.ES are both NSDate objects and self.calendar is a gregorian calendar.

  • When calculating between Nov 1, 2013 and Nov 1, 2013, it provides 0.
  • When calculating between Nov 1, 2013 and Nov 2, 2013, it provides 1.
  • When calculating between Nov 1, 2013 and Nov 3, 2013, it provides 2.
  • When calculating between Nov 1, 2013 and Nov 4, 2013, it provides 2 again!

Here is my output:

    Days: 0 and hours: 0
    Days: 1 and hours: 0
    Days: 2 and hours: 0
    Days: 2 and hours: 24
    Days: 3 and hours: 23

I'd like to be able to determine the number of days between 2 NSDate objects without impact by Daylight Savings Time, as my app doesn't care what local or timezone the user is in. I just want it to tell me that there are 3 days between Nov 1, 2013 and Nov 4, 2013. Any thoughts?

My NSDate objects are created from strings in the format of: 2013-11-01 00:00:00 +0000. Each date has the time set to 00:00:00 with the GMT offset of +0000.

I've thought of two possible options:

  • Use isDaylightSavingTime to check each date and create a new (modified) date offset by 1 hour if it the date is Daylight Savings Time. I'm worried about the added calculation time as my app calculates the date between a given begin date and an array of other dates. This array may have up to 2,000 dates in it. I'm not sure if that's a legit concern or not...
  • create a custom timezone that is not affected by DST. Is this even possible?
4

1 回答 1

2

我可以使用 10 月 27 日左右的日期(英国夏令时开始时)并将时区设置为欧洲/伦敦来确认您的观察。“n 天 24 小时”似乎是一个怪癖(对 bug 的好话,有人忘了携带)。

解决方案 1:使用NSCalendar设置为 UTC。UTC 没有夏令时。

解决方案 2:由于您的所有时间都在午夜,并且最大夏令时班次为 1 小时,因此“一天”介于 23 到 25 小时之间。考虑到这一点,并简单地同时处理怪癖:

daysBetween = [activityComponents day] + ([activityComponents hour] >= 23 ? 1 : 0);

请注意,这有效,因为两个日期的时间相同!

于 2013-11-25T18:09:14.027 回答