Search code examples
iosswiftnsdatensdatecomponents

How to convert NSDateComponents to NSDate?


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


Solution

  • 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]