Try this (in https://dartpad.dev/):
int day = 28;
DateTime day1 = DateTime(2020, 3, day);
DateTime day2 = DateTime(2020, 3, day - 1);
print(day1.difference(day2).inDays);
The result should be 1, getting 0 instead... Replace "day" variable with any other value and it gives the right result (1)...
Is it a bug?
Well, the problem comes down to the return value of difference
which is:
The difference is measured in seconds and fractions of seconds. The difference above counts the number of fractional seconds between midnight at the beginning of those dates. If the dates above had been in local time, not UTC, then the difference between two midnights may not be a multiple of 24 hours due to daylight saving differences.
https://api.dart.dev/stable/2.7.2/dart-core/DateTime/difference.html
So the value we gets from difference
is a Duration
objects containing the difference between the two DateTime
objects in seconds. You can then ask the Duration
to represent this result in days.
The problems is that many countries are shifting their clocks because of daylight saving time in march. In fact, your example are not showing any bugs on my computer since I am in Denmark. So I changed your code into:
void main() {
for (var day = 1; day <= 31; day++) {
DateTime day1 = DateTime(2020, 3, day);
DateTime day2 = DateTime(2020, 3, day - 1);
print('Day $day: inDays: ${day1.difference(day2).inDays} inHours: ${day1.difference(day2).inHours}');
}
}
Which returns the following on my computer:
Day 27: inDays: 1 inHours: 24
Day 28: inDays: 1 inHours: 24
Day 29: inDays: 1 inHours: 24
Day 30: inDays: 0 inHours: 23
Day 31: inDays: 1 inHours: 24
Because we actually removes one hour of the day when we are changing into daylight saving time, the returned duration does not contain 24 hours but 23.