NSDate 一年中的第几天 (swift)

NSDate day of the year (swift)

如何使用 swift 找到一年中的天数?有没有一种我没有看到的简单方法,或者我是否必须找到从 1 月 1 日到当前日期的秒数,然后除以一天中的秒数?

完全没有!!!您所要做的就是使用 NSCalendar 来帮助您进行日历计算,如下所示:

let firstDayOfTheYear  = NSCalendar.currentCalendar().dateWithEra(1, year: NSCalendar.currentCalendar().component(.CalendarUnitYear, fromDate: NSDate()), month: 1, day: 1, hour: 0, minute: 0, second: 0, nanosecond: 0)!   // "Jan 1, 2015, 12:00 AM"

let daysFromJanFirst = NSCalendar.currentCalendar().components(.CalendarUnitDay, fromDate: firstDayOfTheYear, toDate: NSDate(), options: nil).day   // 55

let secondsFromJanFirst = NSCalendar.currentCalendar().components(.CalendarUnitSecond, fromDate: firstDayOfTheYear, toDate: NSDate(), options: nil).second   // 4,770,357

这是将 How do you calculate the day of the year for a specific date in Objective-C? 的答案翻译成 Swift。

Swift 2:

let date = NSDate() // now
let cal = NSCalendar.currentCalendar()
let day = cal.ordinalityOfUnit(.Day, inUnit: .Year, forDate: date)
print(day)

Swift 3:

let date = Date() // now
let cal = Calendar.current
let day = cal.ordinality(of: .day, in: .year, for: date)
print(day)

一年中的第一天为 1,今天(2 月 25 日)为 56 = 31 + 25

... or do I have to find the number of seconds from Jan 1 to the current date and divide by the number of seconds in a day

这是一个错误的做法,因为一天没有固定的时间 秒数(从或到夏令时的转换)。

您可以像这样找到约会后的天数:

let date = NSDate() // your date

let days = cal.ordinalityOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitYear, forDate: date)

println(days)

Swift 3

extension Date {
    var dayOfYear: Int {
        return Calendar.current.ordinality(of: .day, in: .year, for: self)!
    }
}

使用喜欢

Date().dayOfYear