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?
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.
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.
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).
Swift 3
extension Date { var dayOfYear: Int { return Calendar.current.ordinality(of: .day, in: .year, for: self)! } }
use like
Date().dayOfYear
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With