Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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!

like image 275
chuanpham Avatar asked Nov 29 '25 20:11

chuanpham


2 Answers

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';
like image 199
Ivo Beckers Avatar answered Dec 02 '25 10:12

Ivo Beckers


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.

like image 30
Stefano Saitta Avatar answered Dec 02 '25 11:12

Stefano Saitta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!