Problem combining a date and a time into a single NSDate

前端 未结 4 915
梦毁少年i
梦毁少年i 2020-12-15 22:33

I am trying to combine the time value (hours, minutes, seconds) of one NSDate with the date value (day, month, year) of a second NSDate with this m

4条回答
  •  心在旅途
    2020-12-15 23:14

    Here it is in Swift 2

    func combineDateAndTime(date: NSDate, time: NSDate) -> NSDate {
    
        let calendar = NSCalendar.currentCalendar()
        let dateComponents = calendar.components([.Year, .Month, .Day], fromDate: date)
        let timeComponents = calendar.components([.Hour, .Minute, .Second], fromDate: time)
    
        let components = NSDateComponents()
        components.year = dateComponents.year
        components.month = dateComponents.month
        components.day = dateComponents.day
        components.hour = timeComponents.hour
        components.minute = timeComponents.minute
        components.second = timeComponents.second
    
        return calendar.dateFromComponents(components)!
    }
    

提交回复
热议问题