Skip to content

Instantly share code, notes, and snippets.

@majeedyaseen
Created March 16, 2018 18:01
Show Gist options
  • Save majeedyaseen/ec0cefddce4a21cf69d87ec8bc5d8895 to your computer and use it in GitHub Desktop.
Save majeedyaseen/ec0cefddce4a21cf69d87ec8bc5d8895 to your computer and use it in GitHub Desktop.
Combine date and time into a single NSDate in Swift 3
//function to combine date and time from two different date objects.
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 mergedComponments = DateComponents()
mergedComponments.year = dateComponents.year!
mergedComponments.month = dateComponents.month!
mergedComponments.day = dateComponents.day!
mergedComponments.hour = timeComponents.hour!
mergedComponments.minute = timeComponents.minute!
mergedComponments.second = timeComponents.second!
return calendar.date(from: mergedComponments)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment