10

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

pppery
  • 3,731
  • 22
  • 33
  • 46
YMonnier
  • 1,384
  • 2
  • 19
  • 30

4 Answers4

21

Swift 4 :

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

// components is your component name
Bugs
  • 4,491
  • 9
  • 32
  • 41
Saurabh Padwekar
  • 3,888
  • 1
  • 31
  • 37
5

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]
Mundi
  • 79,884
  • 17
  • 117
  • 140
1

The conversion between a date and date components always requires a calendar. You have two options (compare NSCalendar dateFromComponents: vs NSDateComponents date):

  • Assign a calendar to the date components, i.e. add

    components.calendar = calendar
    

    to your getCurrentDateComponent() method. Then

    var d = getCurrentDateComponent().date
    

    works as expected. (Without assigning a calendar to the date components, the date property returns nil, as you observed.)

  • Alternatively, call a calendar method for the conversion:

    let d = NSCalendar.currentCalendar().dateFromComponents(getCurrentDateComponent())
    
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

You need to set the calendar before using NSDateComponents, because without calendar there in no date.

let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: date)
components.calendar = NSCalendar.currentCalendar();
return components
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136