DateTime.add(Duration days) produces wrong date

/*
Bug description: Adding duration of Days to DateTime is consistently WRONG in certain months.
DateTime mysteriously adds 23 hours (in month 11, Nov) in addition to the days
resulting in WRONG date and of course day of week. In a loop it continues with this error
until mysteriously correcting itself a few months later.
In the following test, I’m adding 7 days in the loop and also printing the weekday so that you can
spot the problem easily. Also of course keep an eye on the hours in the dates printed.
Printing several years to prove bug consistency every year, at same month.
[Update: Possibly related to switching back from DST]
*/

void main() {
  int numOfLoops = 40;
  for (int year = 2015; year < 2022; year++) {
    DateTime dateTime = DateTime(year, 10, 1);
    for (int i= 0; i<numOfLoops;i++ ) {
      print ('Starting Year:$year Loop# $i');
      print ('BEFORE ADDING 7 DAYS: $dateTime. \t weekday = ${dateTime.weekday}' );
      dateTime = dateTime.add(Duration(days:7));
      print (' AFTER ADDING 7 DAYS: $dateTime. \t weekday = ${dateTime.weekday}' );
    }
  }
}

Author: Fantashit

1 thought on “DateTime.add(Duration days) produces wrong date

  1. This is working as intended. It is definitely related to daylight saving.

    A Duration of “days” is not actually counting days, as documented on the Duration class. To Duration, a “day” is just 86400 (aka 24 * 60 * 60) seconds. (There is no “month” or “year” concepts on the Duration class because we can’t even assign a fixed number of seconds to those).

    When you add 7 * 86400 seconds to a local time DateTime instance, you are not necessarily adding seven to the calendar date because of daylight saving.

    If you make your DateTime instance be in UTC instead, then you will find that you do add one calendar date per 86400 seconds.
    You should always use UTC dates for calendar date calculations.

Comments are closed.