Given the following method I added to the Date object in an extension:
extension Date { static func -(left: Date, right: Date) -> DateComponents { let components: Set<Calendar.Component> = [ .year, .month, .day, .hour, .minute, .second, //.weekOfYear, // issue! ] let gregorian = Calendar(identifier: .gregorian) let dateComponents = gregorian.dateComponents(components, from: right, to: left) return dateComponents } } And given the following dates (format is Month Day, Year, hh:mm:ss) you get 1:
let day1 = Date(timeIntervalSince1970: 1516003200) // January 15, 2018, 00:00:00 let day2 = Date(timeIntervalSince1970: 1516089600) // January 16, 2018, 00:00:00 let diff = day2 - day1 print(diff.day!) // 1 But given the following dates, you also get 1:
let day3 = Date(timeIntervalSince1970: 1515916800) // January 14, 2018, 00:00:00 let day4 = Date(timeIntervalSince1970: 1516089600) // January 16, 2018, 00:00:00 let diff2 = day4 - day3 print(diff.day!) // 1 So my first question is wondering why the day difference is the same even though one of the pair is 1 day apart and the other is 2 days apart.
Finally, given the following dates, you get the correct number of 14:
let day5 = Date(timeIntervalSince1970: 1516089600) // January 16, 2018, 00:00:00 let day6 = Date(timeIntervalSince1970: 1517299200) // January 30, 2018, 00:00:00 let diff3 = day6 - day5 print(diff3.day!) But if you were to go back to static func -(left:right:) and uncomment .weekOfYear and re run the above block of code with day5 and day6 you get 0 days. So my second question is why I'm getting 0 days if I add the .weekOfYear component to the Set.
I included two screenshots of a playground below, first one with .weekOfYear not included and the second one including .weekOfYear:


print(diff.day!)when you should be printingprint(diff2.day!)day3andday4, testing every time zone, and in all of them, thedaydifference is 2.