Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the number of days in given month and year using swift

Tags:

swift

I want to find the total number days on given month and year. Example: I want to find total number of days on year = 2015, month = 7

like image 521
Shrestha Ashesh Avatar asked Jul 23 '15 14:07

Shrestha Ashesh


People also ask

How do I get current month and year in Swift?

var lastMonthDate = Calendar. current. date(byAdding: . month, value: -1, to: date) calendar.

How do you subtract dates in Swift?

To subtract hours from a date in swift we need to create a date first. Once that date is created we have to subtract hours from that, though swift does not provide a way to subtract date or time, but it provides us a way to add date or date component in negative value.


3 Answers

First create an NSDate for the given year and month:

let dateComponents = NSDateComponents()
dateComponents.year = 2015
dateComponents.month = 7

let calendar = NSCalendar.currentCalendar()
let date = calendar.dateFromComponents(dateComponents)!

Then use the rangeOfUnit() method, as described in Number of days in the current month using iPhone SDK?:

// Swift 2:
let range = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: date)
// Swift 1.2:
let range = calendar.rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: date)

let numDays = range.length
print(numDays) // 31

Update for Swift 3 (Xcode 8):

let dateComponents = DateComponents(year: 2015, month: 7)
let calendar = Calendar.current
let date = calendar.date(from: dateComponents)!

let range = calendar.range(of: .day, in: .month, for: date)!
let numDays = range.count
print(numDays) // 31
like image 185
Martin R Avatar answered Oct 19 '22 21:10

Martin R


Updated for Swift 3.1, Xcode 8+, iOS 10+

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)! //change year it will no of days in a year , change it to month it will give no of days in a current month

// Compute difference in days:
let days = calendar.dateComponents([.day], from: interval.start, to: interval.end).day!
print(days)
like image 19
Abdul Karim Avatar answered Oct 19 '22 19:10

Abdul Karim


In extension format, using self to be able to return the number of days more dynamically (Swift 3).

extension Date {

func getDaysInMonth() -> Int{
    let calendar = Calendar.current

    let dateComponents = DateComponents(year: calendar.component(.year, from: self), month: calendar.component(.month, from: self))
    let date = calendar.date(from: dateComponents)!

    let range = calendar.range(of: .day, in: .month, for: date)!
    let numDays = range.count

    return numDays
}

}
like image 15
spogebob92 Avatar answered Oct 19 '22 19:10

spogebob92