iphonedatetimedatensdatensdateformatter

How to get NSDate day, month and year in integer format?


I want to get the day, month and year components of NSDate in integer form i.e. if the date is 1/2/1988 then I should get 1, 2 and 1988 separately as an integer. How can I do this in iOS? I found the similar question but the method descriptionWithCalendarFormat: gives a warning and seems to be deprecated by now.


Solution

  • Swift

    let components = NSCalendar.currentCalendar().components([.Day, .Month, .Year], fromDate: self)
    let day = components.day
    let month = components.month
    let year = components.year
    

    For convenience you can put this in an NSDate extension and make it return a tuple:

    extension NSDate: Comparable {
    
        var dayMonthYear: (Int, Int, Int) {
            let components = NSCalendar.currentCalendar().components([.Day, .Month, .Year], fromDate: self)
            return (components.day, components.month, components.year)
        }
    }
    

    Now you have to write only:

    let (day, month, year) = date.dayMonthYear
    

    If you wanted to e.g. get only the the year you can write:

    let (_, _, year) = date.dayMonthYear