Home > Software engineering >  How to get list of months between two dates in dart/flutter
How to get list of months between two dates in dart/flutter

Time:07-04

I am trying to get a list of months between two dates in Dart

Example :

Input Date:

    date 1 - 20/12/2011 
    date 2 - 22/08/2012

Now, my expected result should be :

        12/2011
        1/2012
        2/2012
        3/2012
        4/2012
        5/2012
        6/2012
        7/2012
        8/2012

Thanks for your help!

CodePudding user response:

You can do this:

var date1 = DateFormat("dd/MM/yyyy").parse("20/12/2021");
var date2 = DateFormat("dd/MM/yyyy").parse("22/08/2022");
while (date1.isBefore(date2)) {
  print(DateFormat("M/yyyy").format(date1));
  date1 = DateTime(date1.year, date1.month   1);
}

You need

import 'package:intl/intl.dart';

CodePudding user response:

you can use

date1.subtract(Duration(days: 7, hours: 3, minutes: 43, seconds: 56)); 

date1.add(Duration(days: 1, hours: 23)));

to add oder subtract days, months ...or what u like.... then do a if check in a loop or a while loop

something like this:

void main() {
  DateTime a = DateTime.now();
  DateTime b = a.add(Duration(days: 360));
  DateTime c = a;
  
 
  
  while (c.millisecondsSinceEpoch<b.millisecondsSinceEpoch)
  {
    c = c.add(Duration(days:31));
    print('${c.month}/${c.year}');
  }
}
  • Related