Subtract two Arrays in javascript

1

How about the idea would be the subtraction of two dates in javascript to then add it within the function. I show them what I am doing and so they can help me.

var newYear = new Array(12, 5, 2018);


var jhon = {
    name: "Jhon",
    lastName: "Smith",
    job: "Teacher",
    yearOfBirth: new Array(11, 11, 1996),
    calculateAge: function(){

        this.age = this.newYear - this.yearOfBirth;


    }


};

jhon.calculateAge();
console.log(jhon);

As I said before, the idea is to be able to calculate the subtraction of dates and then be able to insert it within the properties of the object.

    
asked by Tomás Blanco 13.05.2018 в 03:16
source

2 answers

1

var date = new Date();

var WakandaKing = {
  name: 'TChalla',
  birthDate: '2000-01-01',
  calcAge: function(){
    return ((date - new Date(this.birthDate)) / 86400000)/365
  },
  country: 'Wakanda'
};

console.log( Math.round(WakandaKing.calcAge() ) );

If you want to calculate a date, create objects of dates, it is not a function of the arrangements to do that operation, I'll give you an example of how you can implement it.

That it serves you

    
answered by 13.05.2018 в 03:46
0

I give you an option using the library Moments.js , which facilitates the handling of dates.

var newYear = moment("2018-05-12");

var jhon = {
  name: "Jhon",
  lastName: "Smith",
  job: "Teacher",
  yearOfBirth: moment("1996-11-11"),
  age: null,
  calculateAge: function(){
    this.age = newYear.diff(this.yearOfBirth, "year");
  }
};

jhon.calculateAge();
console.log(jhon.age);
console.log(jhon.yearOfBirth);//vas a otar que la fecha tiene un formato "extraño"
console.log(jhon.yearOfBirth.format("DD-MM-YYYY"));//de esta manera puedas formatear la fecha.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
answered by 13.05.2018 в 03:50