0

I'm having some issues with Duration.inDays. When I compute the difference in Days between 27th of May to the 18th of May, it is the as the difference in Days between 27th of May to the 18th of May. Here is a code snipped:

final firstDate = DateTime(2022, 3, 18, 0, 0, 0, 0, 0);
final secondDate = DateTime(2022, 3, 27, 0, 0, 0, 0, 0);
final thirdDate = DateTime(2022, 3, 28, 0, 0, 0, 0, 0);

final firstDif = firstDate.difference(secondDate);
final secondDif = firstDate.difference(thirdDate);

print("First Days: ${firstDif.inDays} First Hours: ${firstDif.inHours} Second Days: ${secondDif.inDays} Second Hours: ${secondDif.inHours}");

This is the print statement:

First Days: -9 First Hours: -216 Second Days: -9 Second Hours: -239

As you can see, the difference in hours for the 28th is only -239 hours, not -240 as I would expect. Thus the resulting difference in days is -9 in both cases.

Why is this happening and how can I fix this issue?

Jonas
  • 7,089
  • 15
  • 49
  • 110

1 Answers1

1

The reason that you get 239 hours is that Daylight Savings Time kicked in between the two dates, so one day was 'shorter' by an hour. See the various caveats in the documentation of DateTime and Duration.

To avoid summer time issues, use UTC dates. Replace all your constructors with DateTime.utc.

final firstDate = DateTime.utc(2022, 3, 18, 0, 0, 0, 0, 0);
final secondDate = DateTime.utc(2022, 3, 27, 0, 0, 0, 0, 0);
final thirdDate = DateTime.utc(2022, 3, 28, 0, 0, 0, 0, 0);
Richard Heap
  • 48,344
  • 9
  • 130
  • 112