-1

I have the following code:

func rangeOfPeriod(period: NSCalendarUnit, date: NSDate) -> (NSDate, NSDate) {
        let calendar = NSCalendar.currentCalendar()
        var startDate: NSDate? = nil
        var duration: NSTimeInterval = 0

        calendar.rangeOfUnit(period, startDate: &startDate, interval: &duration, forDate: date)

        let endDate = startDate!.dateByAddingTimeInterval(duration - 1)

        return (startDate!, endDate)
}

When i print the following lines:

print("Day test = \(rangeOfPeriod(.Day, date: NSDate()))")
print("Week test = \(rangeOfPeriod(.WeekOfYear, date: NSDate()))")
print("month test = \(rangeOfPeriod(.Month, date: NSDate()))")
print("Year test = \(rangeOfPeriod(.Year, date: NSDate()))")

All of them work as expected apart from month.

I get 'month test = (2016-03-01 00:00:00 +0000, 2016-03-31 22:59:59 +0000)' as a result and it seems to be missing a hour. For the time for all the others i get '2016-03-26 23:59:59 +0000'.

Any help would be appreciated

Jess Murray
  • 1,273
  • 1
  • 10
  • 32

1 Answers1

1

Maybe there is a confusion about the interval parameter in the rangeOfUnit method.

From the documentation

func rangeOfUnit(_ unit: NSCalendarUnit,
        startDate datep: AutoreleasingUnsafeMutablePointer<NSDate?>,
           interval tip: UnsafeMutablePointer<NSTimeInterval>,
           forDate date: NSDate) -> Bool

.....

tip : Upon return, contains the duration (as NSTimeInterval) of the calendar unit unit that contains the date date


For this month (March 2016) due to Daylight Saving Time change the duration is

31 * 86400.0 - 3600.0 = 2674800.0 

That means there is an hour missing, but it's not specified when.


To get the end of the month this is more accurate

func endOfThisMonth() -> NSDate
{
  let calendar = NSCalendar.currentCalendar()
  let components = NSDateComponents()
  components.day = 1
  let startOfNextMonth = calendar.nextDateAfterDate(NSDate(), matchingComponents: components, options: .MatchNextTime)!
  return calendar.dateByAddingUnit(.Second, value: -1, toDate: startOfNextMonth, options: [])!
}
vadian
  • 274,689
  • 30
  • 353
  • 361