我们可以使用下面的行获取一年中的日期。
let day = cal.ordinalityOfUnit(.Day, inUnit: .Year, forDate: date)
但是,我们如何获得一年中的某天的日期呢?
如果您知道年份,则可以获取DateComponents date属性,如下所示:
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"
或使用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" }