ArunJaganathan
ArunJaganathan

Reputation: 713

How to list all months between two dates using JS?

If I selected any two date,for example var d1 = '2014-05-01'; var d2 = '2017-06-01';

Now I want to show all months between these two dates? Is it possible or not ?

Upvotes: 0

Views: 2433

Answers (2)

Alexandre Gaubil
Alexandre Gaubil

Reputation: 199

I had the same need, but I think there is a simpler (and more less prone to errors because of weird dates) way to do this now using the luxon library. Another advantage of using luxon is that strings are automatically localized when using their formatting functions. Here is how I did it:

const DateTime = luxon.DateTime

let date1 = DateTime.fromISO("2014-05-01")
let date2 = DateTime.fromISO("2017-06-01")

const months = []
while (date1 < date2) {
  months.push(date1.toSeconds())

  // Increase the first date by a month (e.g., from 2014-05-01 
  // to 2014-05-01.
  date1 = date1.plus({ months: 1 })
}

console.log(months)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.min.js"></script>

You can then use the resulting list of timestamps to print the months, for example by doing the following:

const DateTime = luxon.DateTime

let date1 = DateTime.fromISO("2014-05-01")
let date2 = DateTime.fromISO("2017-06-01")

const months = []
while (date1 < date2) {
  months.push(date1.toSeconds())
  date1 = date1.plus({ months: 1 })
}

// Convert the timestamp to a string description.
const monthsDescription = months.map((date) =>
  DateTime.fromSeconds(date).toFormat("yyyy LLLL"))

console.log(monthsDescription)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.min.js"></script>

Upvotes: 0

Emil S. J&#248;rgensen
Emil S. J&#248;rgensen

Reputation: 6366

var namedMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
//Format: yyyy-mm-dd
function stringToDate(datestring) {
  var d = new Date(0);
  d.setHours(2);
  d.setFullYear(parseInt(datestring.substr(0, 4), 10));
  d.setMonth(parseInt(datestring.substr(5, 2), 10));
  d.setDate(parseInt(datestring.substr(8, 2), 10));
  return d;
}

function monthsBetween(from, to, cb) {
  if (cb === void 0) {
    cb = function(month) {};
  }
  //Convert to date objects
  var d1 = stringToDate(from);
  var d2 = stringToDate(to);
  //month counter
  var months = 0;
  //Call callback function with month
  cb(d1.getMonth());
  //While year or month mismatch, reduce by one day
  while (d2.getFullYear() != d1.getFullYear() || d2.getMonth() != d1.getMonth()) {
    var oldmonth = d1.getMonth();
    d1 = new Date(d1.getTime() + 86400000);
    //if we enter into new month, add to month counter
    if (oldmonth != d1.getMonth()) {
      //Call callback function with month
      cb(d1.getMonth());
      months++;
    }
  }
  //return month counter as result
  return months;
}
//test
var d1 = '2014-05-01';
var d2 = '2017-06-01';
console.log(monthsBetween(d1, d2, function(month) {
  console.log(namedMonths[month]);
}), "months between:", d1, "and", d2);

EDIT 1 - Fixed the above snippet to include a callback function

Use the callback to do "by month" operations, like logging it to the console or writing it to your document.

Upvotes: 1

Related Questions