ios8

How to get current day, month and year in NSDate() using Swift?

by
published on
Just so that i never waste any more time in my life on this, this goes here.. Swift 1.x
        let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: date)
        
        let year =  components.year
        let month = components.month
        let day = components.day
Every changing depreciations and swift framework.. just making it more fun!   ------ Updated 25th Dec. As pointed out by Joey in comment below this is not working anymore. Coincidently i was working on something similar just few minutes back, so here is the updated code. [We have to pass the values now as array.] Swift 2.x
        let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components([.Day , .Month , .Year], fromDate: date)
        
        let year =  components.year
        let month = components.month
        let day = components.day
        
        print(year)
        print(month)
        print(day)
  Swift 3.x
//As part of swift 3 apple has removed NS, making things simpler so 
//new code will be:

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

let year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
You can extract various date components using the variables provided here: https://developer.apple.com/reference/foundation/nsdatecomponents