Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate day of the year (swift)

Tags:

ios

swift

nsdate

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?

like image 599
Dan Oswalt Avatar asked Feb 25 '15 06:02

Dan Oswalt


People also ask

How do I increment a date in Swift?

To add more days to a current date object, you can use the Calendar and the DateComponents() Swift structs. print(futureDate!) let currentDate = Date() var dateComponent = DateComponents() dateComponent. day = 1 let futureDate = Calendar.

How do I compare two dates in Swift?

let date1 = Date() let date2 = Date(). addingTimeInterval(100) if date1 == date2 { ... } else if date1 > date2 { ... } else if date1 < date2 { ... } if i want to ignore time. e.g. 2019-05-14 12:08:14 +0000 == 2019-05-14 should return true.


2 Answers

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).

like image 167
Martin R Avatar answered Sep 22 '22 15:09

Martin R


Swift 3

extension Date {     var dayOfYear: Int {         return Calendar.current.ordinality(of: .day, in: .year, for: self)!     } } 

use like

Date().dayOfYear 
like image 20
Adam Smaka Avatar answered Sep 25 '22 15:09

Adam Smaka