Javascript: Get All Months Between Two Dates

JavaScript: get all months between two dates?

This should produce the desired output:

function dateRange(startDate, endDate) {
var start = startDate.split('-');
var end = endDate.split('-');
var startYear = parseInt(start[0]);
var endYear = parseInt(end[0]);
var dates = [];

for(var i = startYear; i <= endYear; i++) {
var endMonth = i != endYear ? 11 : parseInt(end[1]) - 1;
var startMon = i === startYear ? parseInt(start[1])-1 : 0;
for(var j = startMon; j <= endMonth; j = j > 12 ? j % 12 || 11 : j+1) {
var month = j+1;
var displayMonth = month < 10 ? '0'+month : month;
dates.push([i, displayMonth, '01'].join('-'));
}
}
return dates;
}

Just call it with your existing date format:

dateRange('2013-11-01', '2014-06-01')
// ["2013-11-01", "2013-12-01", "2014-01-01", "2014-02-01", "2014-03-01", "2014-04-01", "2014-05-01", "2014-06-01", "2014-07-01", "2014-08-01", "2014-09-01", "2014-10-01", "2014-11-01", "2014-12-01"]

Difference in Months between two dates in JavaScript

The definition of "the number of months in the difference" is subject to a lot of interpretation. :-)

You can get the year, month, and day of month from a JavaScript date object. Depending on what information you're looking for, you can use those to figure out how many months are between two points in time.

For instance, off-the-cuff:

function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}

function monthDiff(d1, d2) {    var months;    months = (d2.getFullYear() - d1.getFullYear()) * 12;    months -= d1.getMonth();    months += d2.getMonth();    return months <= 0 ? 0 : months;}
function test(d1, d2) { var diff = monthDiff(d1, d2); console.log( d1.toISOString().substring(0, 10), "to", d2.toISOString().substring(0, 10), ":", diff );}
test( new Date(2008, 10, 4), // November 4th, 2008 new Date(2010, 2, 12) // March 12th, 2010);// Result: 16
test( new Date(2010, 0, 1), // January 1st, 2010 new Date(2010, 2, 12) // March 12th, 2010);// Result: 2
test( new Date(2010, 1, 1), // February 1st, 2010 new Date(2010, 2, 12) // March 12th, 2010);// Result: 1

How to get full months between two dates in javascript

You can use something like this:

function monthDiff(d1, d2) {    var months;    months = (d2.getFullYear() - d1.getFullYear()) * 12;    months -= d1.getMonth() + 1;    months += d2.getMonth();    return months <= 0 ? 0 : months;}
var result = monthDiff( new Date(2008, 10, 4), new Date(2010, 2, 12) );
document.getElementById("result").innerHTML = result
<span id="result"></span>

How to list all months between two dates using JS?

var namedMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];//Format: yyyy-mm-ddfunction 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;}//testvar 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);

How to get list of months between 2 years in typescript for angular

One way to do this is to think of the Year & Month as one value.
eg. var ym = year * 12 + (month - 1)

If you do this then you can compare the YM value to the next item in the array, if it's below then you can insert a new item into the array between them.

Update, added two utility function to make this easier, YM, will basically convert Year/Month into a linear number, and then RYM will convert this number back into {year, month}, Bonus, I think it makes the code slightly easier to follow too.

Below is an example..

var arr = [
{month: 7, year: 2021, count: 21},
{month: 12, year: 2021, count: 54},
{month: 2, year: 2022, count: 76}
];

/*var arr = [
{month: 11, year: 2021, count: 54},
{month: 2, year: 2022, count: 76}
]; */

const YM = ({year, month}) => year * 12 + month - 1;

const RYM = ym => ({
year: Math.trunc(ym / 12),
month: (ym % 12) + 1
});


function fillSpace(arr) {
let st = 0;
while (st < arr.length -1){
const thisYM = YM(arr[st]);
const nextYM = YM(arr[st + 1]);
if (thisYM + 1 < nextYM)
arr.splice(st + 1, 0, {
...RYM(thisYM + 1),
count: 0
});
st += 1;
}
}

fillSpace(arr);

console.log(arr);

How to list all month between 2 dates with moment.js?

This should do it:

var dateStart = moment('2013-8-31');
var dateEnd = moment('2015-3-30');
var timeValues = [];

while (dateEnd > dateStart || dateStart.format('M') === dateEnd.format('M')) {
timeValues.push(dateStart.format('YYYY-MM'));
dateStart.add(1,'month');
}

javascript get month between two dates

Please use these piece of code to get month difference

var date1=new Date(2017,1,19);//Remember, months are 0 based in JSvar date2=new Date(2017,4,19);var year1=date1.getFullYear();var year2=date2.getFullYear();var month1=date1.getMonth();var month2=date2.getMonth();if(month1===0){ //Have to take into account  month1++;  month2++;}var numberOfMonths=(year2 - year1) * 12 + (month2 - month1) - 1;alert("Number of months "+numberOfMonths+1);

Display months between two dates with different years

You could use Array().fill() to generate all 12 months for all involved years, flatten that, and then slice the relevant part from it. To make sure that the second argument of slice will be a negative (not zero!), even add 12 more months to that. The second argument will then be a value between -23 and -12:

const monthsArr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];  

function monthsBetween(dateFrom, dateTo) {
return Array(dateTo.getFullYear() - dateFrom.getFullYear() + 2)
.fill(monthsArr).flat()
.slice(dateFrom.getMonth(), dateTo.getMonth() - 23);
}

let dateFrom = new Date("2021-09-07");
let dateTo = new Date("2022-03-17");

console.log(monthsBetween(dateFrom, dateTo));

Getting the months between two dates

Apparently PHP's datetime.diff includes the ending day in its calculation. When I actually incremented the end date on the JavaScript side, the numbers all match up. Incrementing the date object itself before comparing them accounts for changing to the next month. The original developer had noticed that that was happening, but he didn't increment the end date correctly. He added another day to the end date's day value, but that wasn't changing to the following month when adding a day to February 28, 2015

This code works as expected:

var getMonthsBetween = function(date1, date2)
{
'use strict';

// Months will be calculated between start and end dates.
// Make sure start date is less than end date.
// But remember if the difference should be negative.
var start_date = date1;
var end_date = date2;
var inverse = false;

if (date1 > date2)
{
start_date = date2;
end_date = date1;
inverse = true;
}

end_date = new Date(end_date); //If you don't do this, the original date passed will be changed. Dates are mutable objects.
end_date.setDate(end_date.getDate() + 1);

// Calculate the differences between the start and end dates
var yearsDifference = end_date.getFullYear() - start_date.getFullYear();
var monthsDifference = end_date.getMonth() - start_date.getMonth();
var daysDifference = end_date.getDate() - start_date.getDate();

return (inverse ? -1 : 1) * (yearsDifference * 12 + monthsDifference + daysDifference/30); // Add fractional month
}


Related Topics



Leave a reply



Submit