如何获得当前/去年的天数

时间:2016-07-06 16:27:32

标签: ios swift nsdate

我想知道当前和去年的天数。我已经设法提出这个代码,它将给我一个开始和结束日期。

然后我使用NSDateComponents来获取当前年份的天数。但我得到的是365,这意味着是去年的天数。

如何核心获得上一年和当年的天数?

 func numOfDaysInYear() {
        let calendar = NSCalendar.currentCalendar()
        var interval = NSTimeInterval(0)
        var startOfYear: NSDate?
        var endOfYear: NSDate!
        calendar.rangeOfUnit(.Year, startDate: &startOfYear, interval: &interval, forDate: NSDate())
        endOfYear = startOfYear?.dateByAddingTimeInterval(interval - 1)


        let comp = calendar.components(.Day, fromDate: startOfYear!, toDate: endOfYear, options: .MatchFirst)
        print(comp.day)
    }

2 个答案:

答案 0 :(得分:1)

 endOfYear = startOfYear?.dateByAddingTimeInterval(interval - 1)

在当前年份的中给出日期,以及它与...的区别 startOfYear为365天,23小时59秒,因此结果为365。

你想要的是

let startOfNextYear = startOfYear!.dateByAddingTimeInterval(interval)
let comp = calendar.components(.Day, fromDate: startOfYear!, toDate: startOfNextYear, options: .MatchFirst)
print(comp.day)

为2016年的闰年提供了正确的输出366

要获得上一年的结果,只需替换当前数据即可 {“1}}日期”一年前“:

NSDate()

答案 1 :(得分:1)

替代方法

let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.day = 1
components.month = 1
let nextFirstJanuar = calendar.nextDateAfterDate(NSDate(), matchingComponents: components, options: .MatchNextTime)!
let thisFirstJanuar = calendar.nextDateAfterDate(nextFirstJanuar, matchingComponents: components, options: [.MatchNextTime, .SearchBackwards])!
let lastFirstJanuar = calendar.nextDateAfterDate(thisFirstJanuar, matchingComponents: components, options: [.MatchNextTime, .SearchBackwards])!

let daysInThisYear = calendar.components(.Day, fromDate: thisFirstJanuar, toDate: nextFirstJanuar, options: []).day
let daysInLastYear = calendar.components(.Day, fromDate: lastFirstJanuar, toDate: thisFirstJanuar, options: []).day