We can get day of year for date using below line.
let day = cal.ordinalityOfUnit(.Day, inUnit: .Year, forDate: date)
But how can we get the date from day of year?
If you display a date with print(Date()) you'll get output like 2018-11-17 23:38:02 +0000 (The +0000 bit is the offset from UTC. An offset of 0000 from UTC means the date/time is expressed in the UTC time zone.)
Swift – Get Current Date Only To get only current date, containing day, month and year, use Date and DateFormatter . Date returns current point in time, while DateFormatter with specified dateFormat formats this Date value to required format, like in this case returning only date (day, month and year).
The return value of a date generated by DateFormatter 's date(from:) method is an optional. If nil is returned the date is invalid, otherwise it's valid. A Date cannot be instantiated with an invalid date string that is outside of the realm of real calendar dates.
If you know the year you can get DateComponents date property as follow:
extension Calendar {
static let iso8601 = Calendar(identifier: .iso8601)
}
let now = Date()
let day = Calendar.iso8601.ordinality(of: .day, in: .year, for: now)! // 121
let year = Calendar.iso8601.component(.year, from: now) // 2017
let date = DateComponents(calendar: .iso8601, year: year, day: day).date // "May 1, 2017, 12:00 AM"
or using DateFormatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy D"
if let date = dateFormatter.date(from: "\(year) \(day)") {
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
dateFormatter.string(from: date) // "May 1, 2017, 12:00 AM"
}
You cannot go the other way. Going from a date to a day of the year discards all other information, you are left with only the day of the year (you no longer know what year). To go back to a full date you would have to make assumptions about the year the day was in.
The answer that @LeoDabus gave is more succinct than this, so it is perhaps the better choice. Having said that, this is the code that I would have used:
let dateComponents = NSDateComponents();
dateComponents.year = 2015
dateComponents.day = day
let calendar = NSCalendar.currentCalendar()
let date = calendar.dateFromComponents(dateComponents)
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