问题
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
回答1:
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]
回答2:
Swift 4 :
let date = NSCalendar.current.date(from: components)
// components is your component name
回答3:
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
回答4:
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. Thenvar d = getCurrentDateComponent().date
works as expected. (Without assigning a calendar to the date components, the
date
property returnsnil
, as you observed.)Alternatively, call a calendar method for the conversion:
let d = NSCalendar.currentCalendar().dateFromComponents(getCurrentDateComponent())
来源:https://stackoverflow.com/questions/31287638/nsdatecomponents-to-nsdate-swift