Created
January 26, 2022 18:20
-
-
Save nicodioso/9c3fc8052488fe40544f87a9ac06db40 to your computer and use it in GitHub Desktop.
Combine two dates specify which components you want to retain from each one
This file contains hidden or 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
extension Date { | |
/// Note: Any duplicate found from 2 components will return nil | |
func combine(_ date1Comp: Set<Calendar.Component>, with date2: Date, components date2Comp: Set<Calendar.Component>) -> Date? { | |
// Check if has duplicates | |
let date1CompDict: [Calendar.Component: Bool] = { | |
var dict: [Calendar.Component: Bool] = [:] | |
date1Comp.forEach{ dict[$0] = true } | |
return dict | |
}() | |
for component in date2Comp { | |
if date1CompDict[component] != nil { | |
print("found duplicate") | |
return nil | |
} | |
} | |
let cal = Calendar.current | |
let d1C = cal.dateComponents(date1Comp, from: self) | |
let d2C = cal.dateComponents(date2Comp, from: date2) | |
var mergedComponents = DateComponents() | |
mergedComponents.year = d1C.year != nil ? d1C.year: d2C.year | |
mergedComponents.month = d1C.month != nil ? d1C.month: d2C.month | |
mergedComponents.day = d1C.day != nil ? d1C.day: d2C.day | |
mergedComponents.hour = d1C.hour != nil ? d1C.hour: d2C.hour | |
mergedComponents.minute = d1C.minute != nil ? d1C.minute: d2C.minute | |
mergedComponents.second = d1C.second != nil ? d1C.second: d2C.second | |
return cal.date(from: mergedComponents) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment