chuanpham
chuanpham

Reputation: 469

How to get list of months between two dates in dart/flutter

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!

Upvotes: 3

Views: 1730

Answers (3)

Stefano Saitta
Stefano Saitta

Reputation: 2014

Not exactly what OP has asked for, but I wanted to share this solution which takes me a while.

This solution also considers the day, and handle correctly the case for February 28.

  static List<DateTime> extractMonthsInRange(DateTime from, DateTime to) {
    //0. save day of from date
    var daysInFromDate = from.day;
    List<DateTime> monthsInRange = [DateTime(from.year, from.month)];

    //1. get a list of months between 2 dates (without days)
    while (from.isBefore(DateTime(to.year, to.month - 1))) {
      var newFrom = DateTime(from.year, from.month + 1);
      monthsInRange.add(newFrom);
      from = newFrom;
    }

    //2. iterate months
    return monthsInRange.map((month) {
      var _lastDayOfMonth = lastDayOfMonth(month);
      //2.  if the day of the from date is < then the day of the last day of the month using the daysInFromDate
      if (daysInFromDate < _lastDayOfMonth.day) {
        return DateTime(month.year, month.month, daysInFromDate);
      }
      //3.  else save the last day of the month (means that the month has less days)
      return _lastDayOfMonth;
    }).toList();
  }

  /// The last day of a given month
  static DateTime lastDayOfMonth(DateTime month) {
    var beginningNextMonth = (month.month < 12)
        ? DateTime(month.year, month.month + 1, 1)
        : DateTime(month.year + 1, 1, 1);
    return beginningNextMonth.subtract(Duration(days: 1));
  }

Please feel free to improve my code in the comments.

Upvotes: 1

Maurice Raguse
Maurice Raguse

Reputation: 4567

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}');
  }
}

Upvotes: 0

Ivo
Ivo

Reputation: 23164

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';

Upvotes: 8

Related Questions