Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateComponents to NSDate - Swift

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...

like image 598
YMonnier Avatar asked Jul 08 '15 08:07

YMonnier


2 Answers

Swift 4 :

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

// components is your component name
like image 132
Saurabh Padwekar Avatar answered Nov 19 '22 11:11

Saurabh Padwekar


That's how I do it:

let allUnits = NSCalendarUnit(rawValue: UInt.max)
return UICalendar.currentCalendar().components(allUnits, fromDate: NSDate())

Note that in Swift 2.0 the bitwise OR operator | is not used any more, instead the NSCalendarUnit conforms to the OptionSetType format:

let timeUnits : NSCalendarUnit = [.Hour, .Minute, .Second]
like image 5
Mundi Avatar answered Nov 19 '22 09:11

Mundi