2

Is there any methods available for NSDate/NSCalendar to calculate the number of days in the current month and current year ?

The only thing I saw is to get the number of days from a given date or between two dates.
Is this the only way ?

Adrian
  • 19,440
  • 34
  • 112
  • 219
  • 1
    But I need the current month/year, not a given month and I actually don't see how the number of days in a year is calculated. – Adrian Jan 17 '16 at 20:44
  • I do wish people can justify the down votes, so I can learn from my mistakes, but from my point of view this is a great question to which I couldn't find an answer yet on stackoverflow. – Adrian Jan 17 '16 at 20:52
  • 1
    I closed as a duplicate because I assumed that the linked-to answer works before both months and years. Then I realized that that is not the case, therefore I have reopened the question. Sorry for the confusion. – Martin R Jan 17 '16 at 20:53

2 Answers2

11

Here is a method which works for both months and years:

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)

(You may want to add some error checking instead of forcibly unwrapping optionals.)


Update for 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)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    Yep, this works for both month and year (just by changing the .Year field inside rangeOfUnit). Thanks. – Adrian Jan 17 '16 at 21:00
4
let date = NSDate()
let cal = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian)!
let days = cal.rangeOfUnit(.Day, inUnit: .Month, forDate: date)

print("\(days) in the month of \(date)")
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • 1
    Thanks Michael. That works great. How can I calculate the number of days in a year ? I tried same code but with .Year instead of .Month for inUnit field, but it doesn't seem to work. – Adrian Jan 17 '16 at 20:49