Problem combining a date and a time into a single NSDate

前端 未结 4 910
梦毁少年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:12

    Swift 3 extension:

    func combineDateAndTime(date: Date, time: Date) -> Date {
    
        let calendar = NSCalendar.current
    
        let dateComponents = calendar.dateComponents([.year, .month, .day], from: date)
        let timeComponents = calendar.dateComponents([.hour, .minute, .second], from: time)
    
        var components = DateComponents()
        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.date(from: components)!
    }
    

提交回复
热议问题