NSDateComponents to NSDate - Swift

YMonnier picture YMonnier · Jul 8, 2015 · Viewed 9.9k times · Source

I have this function :

private func getCurrentDateComponent() -> NSDateComponents {
        let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: date)
        return components
    }

When I call it and I use the function date

var d = this.getCurrentDateComponent().date

I don't know why the variable d is nil...

Thank you for your help

Ysee

Answer

Saurabh Padwekar picture Saurabh Padwekar · Mar 14, 2018

Swift 4 :

let date = NSCalendar.current.date(from: components) 

// components is your component name