7

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?

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Vijay
  • 791
  • 1
  • 8
  • 23
  • What's your use case? In other words, what info do you have and what info are you hoping to obtain? – matt Oct 22 '15 at 18:17
  • @matt I'm loading all the date of year in tableview. so that i've number of row as 365 as hard coded. In cell for row, using indexpath i need to get the date. – Vijay Oct 22 '15 at 18:21
  • Then why didn't you save the date in your data model to start with? That way, all you'd have to do is look at that index of the data model array. Your question makes no sense; you yourself _had_ the information you're after and threw it away. Why did you do that? – matt Oct 22 '15 at 18:33
  • 1
    @matt I think you have not get my info. I've no info other than 365 days. In this how will you have the date model? – Vijay Oct 22 '15 at 18:39
  • You said "I'm loading all the date of year in tableview". So you must have _had_ a date of year. I'm saying: keep it. Don't let go of it. – matt Oct 22 '15 at 18:40
  • I mean I need to load all the date of year. – Vijay Oct 22 '15 at 18:50

3 Answers3

11

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"
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
5

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)
Charles A.
  • 10,685
  • 1
  • 42
  • 39
1

Updated for Swift 4:

let dateComponents = NSDateComponents();
dateComponents.year = 2018
dateComponents.day = someDay
let calendar = NSCalendar.current
let date = calendar.date(from: dateComponents as DateComponents)
ICL1901
  • 7,632
  • 14
  • 90
  • 138