Kobe - 1 year ago 50

iOS Question

I want to find out the number of days from current and last year. I have managed to come up with this code which will give me a starting and ending date.

Then I use

`NSDateComponents`

`365`

How can I corectly get the number of days for last and current year ?

`func numOfDaysInYear() {`

let calendar = NSCalendar.currentCalendar()

var interval = NSTimeInterval(0)

var startOfYear: NSDate?

var endOfYear: NSDate!

calendar.rangeOfUnit(.Year, startDate: &startOfYear, interval: &interval, forDate: NSDate())

endOfYear = startOfYear?.dateByAddingTimeInterval(interval - 1)

let comp = calendar.components(.Day, fromDate: startOfYear!, toDate: endOfYear, options: .MatchFirst)

print(comp.day)

}

Answer Source

```
endOfYear = startOfYear?.dateByAddingTimeInterval(interval - 1)
```

gives a date *within* the current year, and its difference to
`startOfYear`

is 365 days, 23 hours and 59 seconds, and therefore the result is 365.

What you want is

```
let startOfNextYear = startOfYear!.dateByAddingTimeInterval(interval)
let comp = calendar.components(.Day, fromDate: startOfYear!, toDate: startOfNextYear, options: .MatchFirst)
print(comp.day)
```

which gives the correct output `366`

for the leap year 2016.

To get results for the previous year, just replace the current data
`NSDate()`

by a date "one year ago":

```
calendar.dateByAddingUnit(.Year, value: -1, toDate: NSDate(), options: [])
```