Last active
October 6, 2021 13:22
-
-
Save justinmfischer/0a6edf711569854c2537 to your computer and use it in GitHub Desktop.
Combine date and time into a single NSDate in Swift 2.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func combineDateWithTime(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 mergedComponments = NSDateComponents() | |
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.dateFromComponents(mergedComponments) | |
} |
Swift 5 version, typo fixed and without force unwrapping:
func combineDateWithTime(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 mergedComponents = DateComponents()
mergedComponents.year = dateComponents.year
mergedComponents.month = dateComponents.month
mergedComponents.day = dateComponents.day
mergedComponents.hour = timeComponents.hour
mergedComponents.minute = timeComponents.minute
mergedComponents.second = timeComponents.second
return calendar.date(from: mergedComponents)
}
Genius! Thanks so much, you saved so much time for all of us!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After multiple year it still is a very nice solution. Thanks