NSDateComponents to NSDate - Swift

ぐ巨炮叔叔 提交于 2021-02-18 21:09:19

问题


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


来源:https://stackoverflow.com/questions/31287638/nsdatecomponents-to-nsdate-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!