Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Get date from day of year

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?

like image 943
Vijay Avatar asked Oct 22 '15 18:10

Vijay


People also ask

How do I print the day in Swift?

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

How do I get todays date in Swift?

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

How do you check whether a date is valid or not in Swift?

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.


2 Answers

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"
}
like image 111
Leo Dabus Avatar answered Sep 28 '22 01:09

Leo Dabus


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)
like image 44
Charles A. Avatar answered Sep 28 '22 01:09

Charles A.