1

I have a strange bug in my app when subtracting dates. I'm using a daterangepicker to get two dates. I'm then using this simple function:

int subDates(DateTime a, DateTime b) { return a.difference(b).inDays;}

if I select 1st March - 8th March it returns 7 days (correct) if I select 1st March - 31st March it returns 29 days (incorrect)

This only happens in March and it starts showing incorrect from the 28th day.

1st - 27th = 26 days (correct)

1st - 28th = 26 days (incorrect)

Lee Casey
  • 183
  • 10
  • There is an adjustment for Daylight Saving Time that occurs during that period in your locale. If you do not want that, then use UTC `DateTime`s. – jamesdlin Feb 20 '22 at 19:14
  • Hi @jamesdlin thanks for your suggestion. I've converted the DateTimes with .toUTC() and the calculations look correct. However(!)... now when I select 31st March in the daterangepicker it returns 30th March. Do I have to do something to the DateRangePicker? – Lee Casey Feb 20 '22 at 19:47
  • 1
    If you start with two local `DateTime` objects and use `.toUtc()` on them, then there will be no difference in behavior. `.toUtc()` will return a UTC `DateTime` object that represents that same moment in time as the original. Since the original `DateTime` objects are not an exact number of days apart (due to DST), then the ones converted to UTC also will not be an exact number of days apart. You will need to do `DateTime.utc(a.year, a.month, a.day).difference(DateTime.utc(b.year, b.month, b.day)).inDays`. – jamesdlin Feb 20 '22 at 19:51
  • works perfectly and makes sense now. Thank you so much! – Lee Casey Feb 20 '22 at 20:17

0 Answers0