Subtract dates in js [duplicate]


Hi, I would like to know how I can subtract two date objects. I have a variable date of birth and I want to subtract the current day in order to get the years of difference ...

    var f = new Date();
    var xf = (f.getDate() + "/" + (f.getMonth() +1) + "/" + f.getFullYear());
    var xy = 1981-11-17;
    var x = xf - xy; //¿se puede algo así?

can I do something like that ???

asked by E.Rawrdríguez.Ophanim 09.04.2018 в 21:28

3 answers


You can also use the following mode, through getTime that a   from the date 1970/01/01 calculate the past milliseconds and with   the division that I show you get the days of difference between a date   and another

let fecha1 = new Date('2016/08/12');
let fecha2 = new Date()

let resta = fecha2.getTime() - fecha1.getTime()
console.log(Math.round(resta/ (1000*60*60*24)))

60 sec that has one minute * 60 minutes that has one hour * 24 hrs   who regularly holds a day.


Multiplication per 1000 is to reduce three quantities at the time   end of the result

answered by 09.04.2018 / 22:29

If you add or subtract dates must be in its format, you can also add / subtract days

var f = new Date();
var xy = new Date("1981-11-17");
var x = new Date(f.getDate() - xy.getDate());
//sumando dias
f.setDate(f.getDate() + 3); 
//restando dias
x.setDate(x.getDate() - 3 );
answered by 09.04.2018 в 21:55

You can use the library moment.js

It is very easy to use and helps you with all these calcluos.


For example you can do it in the following way:

var a = moment().subtract(1, 'day');
var b = moment().add(1, 'day');


answered by 09.04.2018 в 22:03