Reputation: 460
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
:
Upvotes: 0
Views: 157
Reputation: 3802
In the following code
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
you are using diff.day
when in fact you should be using diff2.day
As for your second issue, the calendar will return date components by assigning from the maximum to minimum. That is to say that when you add weekOfYear
, it assigns a value of 2 to weekOfYear
. If you were to print out diff3.weekOfYear
, you will get 2 (because the dates come up to be 2 weeks). Since there are no days left behind after the date is converted into weeks, you get 0 days for diff3.day
. If you were to use the dates Jan 16th
and Jan 31st
, you would get a value of 2 for week and 1 for day
Upvotes: 3