[英]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? 但是,我们如何获得一年中的某天的日期呢?
If you know the year you can get DateComponents date property as follow: 如果您知道年份,则可以获取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"
or using DateFormatter 或使用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. @LeoDabus给出的答案比这更简洁,因此也许是更好的选择。 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)
Updated for Swift 4: 为Swift 4更新:
let dateComponents = NSDateComponents();
dateComponents.year = 2018
dateComponents.day = someDay
let calendar = NSCalendar.current
let date = calendar.date(from: dateComponents as DateComponents)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.