zbnrg zbnrg - 4 months ago 10
iOS Question

NSDate day of the year (swift)

How might the day number of the year be found with swift? Is there a simple way that I'm not seeing, or do I have to find the number of seconds from Jan 1 to the current date and divide by the number of seconds in a day?

Answer

This is a translation of the answer to How do you calculate the day of the year for a specific date in Objective-C? to Swift.

Swift 2:

let date = NSDate() // now
let cal = NSCalendar.currentCalendar()
let day = cal.ordinalityOfUnit(.Day, inUnit: .Year, forDate: date)
print(day)

Swift 3:

let date = Date() // now
let cal = Calendar.current
let day = cal.ordinality(of: .day, in: .year, for: date)
print(day)

This gives 1 for the first day in the year, and 56 = 31 + 25 for today (Feb 25).

... or do I have to find the number of seconds from Jan 1 to the current date and divide by the number of seconds in a day

This would be a wrong approach, because a day does not have a fixed number of seconds (transition from or to Daylight Saving Time).

Comments