Difference Between Two Dates in Years, Months, Days in JavaScript

How to get difference between 2 Dates in Years, Months and days using moment.js

Moment.js can't handle this scenario directly. It does allow you to take the difference between two moments, but the result is an elapsed duration of time in milliseconds. Moment does have a Duration object, but it defines a month as a fixed unit of 30 days - which we know is not always the case.

Fortunately, there is a plugin already created for moment called "Precise Range", which does the right thing. Looking at the source, it does something similar to torazaburo's answer - but it properly accounts for the number of days in the month to adjust.

After including both moment.js and this plugin (readable-range.js) in your project, you can simply call it like this:

var m1 = moment('2/22/2013','M/D/YYYY');
var m2 = moment('4/5/2014','M/D/YYYY');
var diff = moment.preciseDiff(m1, m2);
console.log(diff);

The output is "1 year 1 month 14 days"

I want to get the difference between two dates in years, months and days

Looks like you are already using moment.js, I suggest you take a look at their durat section on the docs as it provides a very nice way to do what you need.

For your use case, I believe this solves your problem:

let m = moment(selectDate.value);
let applyingDate = m.add(5,"years");
let cur = moment();

const diffDuration = moment.duration(applyingDate.diff(cur))

return [
diffDuration.years(),
diffDuration.months(),
diffDuration.days()
]

It's very similar to this fiddle I created

Obtain difference between two dates in years, months, days in JavaScript

so this is my function, this receive two dates, do all the work and return a json with 3 values, years, months and days.

var DifFechas = {};

// difference in years, months, and days between 2 dates
DifFechas.AMD = function(dIni, dFin) {
var dAux, nAnos, nMeses, nDias, cRetorno
// final date always greater than the initial
if (dIni > dFin) {
dAux = dIni
dIni = dFin
dFin = dAux
}
// calculate years
nAnos = dFin.getFullYear() - dIni.getFullYear()
// translate the initial date to the same year that the final
dAux = new Date(dIni.getFullYear() + nAnos, dIni.getMonth(), dIni.getDate())
// Check if we have to take a year off because it is not full
if (dAux > dFin) {
--nAnos
}
// calculate months
nMeses = dFin.getMonth() - dIni.getMonth()
// We add in months the part of the incomplete Year
if (nMeses < 0) {
nMeses = nMeses + 12
}
// Calculate days
nDias = dFin.getDate() - dIni.getDate()
// We add in days the part of the incomplete month
if (nDias < 0) {
nDias = nDias + this.DiasDelMes(dIni)
}
// if the day is greater, we quit the month
if (dFin.getDate() < dIni.getDate()) {
if (nMeses == 0) {
nMeses = 11
}
else {
--nMeses
}
}
cRetorno = {"años":nAnos,"meses":nMeses,"dias":nDias}
return cRetorno
}

DifFechas.DiasDelMes = function (date) {
date = new Date(date);
return 32 - new Date(date.getFullYear(), date.getMonth(), 32).getDate();
}

hope this help people looking for a solution.

this is a new version that other guy did, seems to have no erros, hope this works better

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

Get difference of 2 dates in years, months, days, but answer is always off by a couple days/months

A year does not always have 365 days. Compared to the web site you refer to, there is also another difference:

Usually when people speak of "today it is exactly 1 month ago", they mean it was on the same month-date. So 14 March comes exactly 1 month after 14 February, and 14 April comes exactly 1 month after 14 March. This means the length of what a "month" is, depends on what your reference point is. In the example, the first difference is 28 days (in non-leap years), while the second is 31 days.

A solution that comes close to the results you get on the web site, can be achieved with this code:

function dateDiff(a, b) {

// Some utility functions:

const getSecs = dt => (dt.getHours() * 24 + dt.getMinutes()) * 60 + dt.getSeconds();

const getMonths = dt => dt.getFullYear() * 12 + dt.getMonth();

// 0. Convert to new date objects to avoid side effects

a = new Date(a);

b = new Date(b);

if (a > b) [a, b] = [b, a]; // Swap into order



// 1. Get difference in number of seconds during the day:

let diff = getSecs(b) - getSecs(a);

if (diff < 0) {

b.setDate(b.getDate()-1); // go back one day

diff += 24*60*60; // compensate with the equivalent of one day

}

// 2. Get difference in number of days of the month

let days = b.getDate() - a.getDate();

if (days < 0) {

b.setDate(0); // go back to (last day of) previous month

days += b.getDate(); // compensate with the equivalent of one month

}

// 3. Get difference in number of months

const months = getMonths(b) - getMonths(a);

return {

years: Math.floor(months/12),

months: months % 12,

days,

hours: Math.floor(diff/3600),

minutes: Math.floor(diff/60) % 24,

seconds: diff % 60

};

}

// Date to start on

var startDate = new Date("Jun 5, 2011 00:00:00");

// Update the count every 1 second

setInterval(function() {

const diff = dateDiff(startDate, new Date);

const str = Object.entries(diff).map(([name, value]) =>

value > 1 ? value + " " + name : value ? value + " " + name.slice(0, name.length-1) : ""

).filter(Boolean).join(", ") || "0 seconds";

document.getElementById("demo").textContent = str;

}, 1000);
<div id="demo"></div>

Moment.js - Get difference in two birthdays in years, months and days

You could get the difference in years and add that to the initial date; then get the difference in months and add that to the initial date again.

In doing so, you can now easily get the difference in days and avoid using the modulo operator as well.

Example Here

var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);

var years = a.diff(b, 'year');
b.add(years, 'years');

var months = a.diff(b, 'months');
b.add(months, 'months');

var days = a.diff(b, 'days');

console.log(years + ' years ' + months + ' months ' + days + ' days');
// 8 years 5 months 2 days

I'm not aware of a better, built-in way to achieve this, but this method seems to work well.



Related Topics



Leave a reply



Submit