斯威夫特 - 从一年中获取日期

Vij*_*jay 4 macos nscalendar ios swift swift3

我们可以使用下面的线获得日期的日期.

let day = cal.ordinalityOfUnit(.Day, inUnit: .Year, forDate: date)
Run Code Online (Sandbox Code Playgroud)

但是我们如何才能从一年中获取日期?

Leo*_*bus 7

如果您知道年份,您可以获得DateComponents日期属性,如下所示:

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"
Run Code Online (Sandbox Code Playgroud)

或使用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"
}
Run Code Online (Sandbox Code Playgroud)


Cha*_* A. 5

你不能走另一条路。从日期到一年中的某一天会丢弃所有其他信息,您只剩下一年中的哪一天(您不再知道是哪一年)。要返回完整的日期,您必须对这一天所在的年份做出假设。

@LeoDabus 给出的答案比这更简洁,所以它可能是更好的选择。话虽如此,这是我会使用的代码:

let dateComponents = NSDateComponents();
dateComponents.year = 2015
dateComponents.day = day
let calendar = NSCalendar.currentCalendar()
let date = calendar.dateFromComponents(dateComponents)
Run Code Online (Sandbox Code Playgroud)