如何计算当月/年的天数

时间:2016-01-17 20:34:08

标签: ios swift

NSDate/NSCalendar是否有任何方法可以计算当月和当年的天数?

我唯一看到的是从给定日期或两个日期之间获得的天数 这是唯一的方法吗?

2 个答案:

答案 0 :(得分:8)

这是一种适用于月份和年份的方法:

let calendar = NSCalendar.currentCalendar()
let date = NSDate()

// Calculate start and end of the current year (or month with `.Month`):
var startOfInterval : NSDate?
var lengthOfInterval = NSTimeInterval()
calendar.rangeOfUnit(.Year, startDate: &startOfInterval, interval: &lengthOfInterval, forDate: date)
let endOfInterval = startOfInterval!.dateByAddingTimeInterval(lengthOfInterval)

// Compute difference in days:
let days = calendar.components(.Day, fromDate: startOfInterval!, toDate: endOfInterval, options: [])
print(days)

(您可能希望添加一些错误检查而不是强行解包 自选。)

更新 Swift 3:

let calendar = Calendar.current
let date = Date()

// Calculate start and end of the current year (or month with `.month`):
let interval = calendar.dateInterval(of: .year, for: date)!

// Compute difference in days:
let days = calendar.dateComponents([.day], from: interval.start, to: interval.end).day!
print(days)

答案 1 :(得分:3)

let date = NSDate()
let cal = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian)!
let days = cal.rangeOfUnit(.Day, inUnit: .Month, forDate: date)

print("\(days) in the month of \(date)")