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) | |
} |
Thank you
Swift 3 version
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 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)
}
Thanks. Save a lot of my time :) 👍
Searched for this piece of code for days. Thanks m8
Thankyou Saved my Day. :) 👍
Thanks! How should we create the properties for date and time?
Worked!!! 👍 💯
After multiple year it still is a very nice solution. Thanks
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
Thanks for posting this. It was a big help.