1

I'm trying make loop 12 times as months in year

for (var i = 1; i <= 12; i++) {
    DateTime.now().add(Duration(days: (i * 30))).toIso8601String())
}

my code is worked correctly but it's give a different days like

If I run loop in today 10 Dec it will give me that

  • 9 January
  • 8 February
  • 9 march

I want a result like that

  • 10 January
  • 10 February
  • 10 march

Answer : I Found my answer of my question here in that package jiffy

dateOfCreated = Jiffy(dateOfCreated).add(months: 1);
Mahmoud Niypoo
  • 1,598
  • 5
  • 24
  • 41

2 Answers2

1

In the loop you add 30 days to current date, but there are months with 31/29/28 days also. So you should add month's length to get next 10th or else date

void main() {
    var now = DateTime.now();
    for (var i = 1; i <= 12; i++) {
      final lastDay = DateTime(now.year, now.month + 1, 0).day;
      now = now.add(Duration(days: lastDay));
      print(now.toIso8601String());
    }
}

dartpad

enter image description here

Kirill Matrosov
  • 5,564
  • 4
  • 28
  • 39
1

This should work for you...

final now = DateTime.now();
for(int i = 1; i<= 12; i++){
   print(DateTime(now.year, now.month + i, now.day).toIso8601String());
}

enter image description here

Kalpesh Kundanani
  • 5,413
  • 4
  • 22
  • 32