I am trying to add days to a date but I don't understand the result, here is my code :

void testDate(){
  DateTime start = DateTime(2019,10,1);
  DateTime end = DateTime(2019,11,1);

  List<DateTime> list = new List();
  DateTime current = DateTime.fromMillisecondsSinceEpoch(start.millisecondsSinceEpoch);

  while(current.isBefore(end)){
    list.add(DateTime.fromMillisecondsSinceEpoch(current.millisecondsSinceEpoch));
    Duration duration = Duration(days:3);
    current = current.add(duration);
    print(current);
    current = DateTime(current.year,current.month,current.day);
  }
}

I got this result :

2019-10-04 00:00:00.000
2019-10-07 00:00:00.000
2019-10-10 00:00:00.000
2019-10-13 00:00:00.000
2019-10-16 00:00:00.000
2019-10-19 00:00:00.000
2019-10-22 00:00:00.000
2019-10-25 00:00:00.000
2019-10-27 23:00:00.000
2019-10-29 23:00:00.000
2019-11-01 00:00:00.000

Why 2019-10-25 00:00:00.000 + 3 days = 2019-10-27 23:00:00.000 ? it should be 2019-10-28 00:00:00.000


Solution 1: Fernando Rocha

The Documentation states that:

"Notice that the duration being added is actually 50 * 24 * 60 * 60 seconds. If the resulting DateTime has a different daylight saving offset than this, then the result won't have the same time-of-day as this, and may not even hit the calendar date 50 days later.

Be careful when working with dates in local time."

Probably there's a daylight saving starting between

2019-10-25 00:00:00.000

2019-10-27 23:00:00.000

check it out at:

https://api.flutter.dev/flutter/dart-core/DateTime/add.html


Solution 2: Mahdi Arabpour

You should use DateTime constructor to add days. it has this feature that if you provide a value that exceeds the current time context such as a 32nd day of the month, it automatically switches to the first day of the next month.

  const daysToAdd = 3;

  current = DateTime(
    current.year,
    current.month,
    current.day + daysToAdd,
  );

you can also subtract days:

  current = DateTime(
    current.year,
    current.month,
    current.day - 150,
  );

checkout this article: https://www.flutterclutter.dev/flutter/troubleshooting/datetime-add-and-subtract-daylight-saving-time/2021/2317/