Home > Mobile >  Date Calculated Incorrectly
Date Calculated Incorrectly

Time:04-07

I'm trying to take someone's birthday and find the day that he/she turns 65. I have the following code but the calculation seems off. For example, if I use the birthday 11/15/1957 I should get 11/15/2022 as the 65th birthday. However, I'm getting 8/9/1982 (which is incorrect) instead.

Am I missing something?

function convertDate(birthday) {

var usethisdate = new Date(birthday);

//let's start by finding the person's 65th birthday

var birthdaysixtyfive = new Date(usethisdate.setMonth(usethisdate.getMonth() 780));
console.log("65th birthday: ",birthdaysixtyfive);
}

CodePudding user response:

Just add 65 to the provided year. And you'll get the result. Below code should do the work.

let birthDay = new Date('11/15/1957')

function getDay(birthDay){
  let birthYear = birthDay.getFullYear()   65
  let birthArr = birthDay.toDateString().split(' ')
  let calculatedDay = new Date(`${birthYear}-${birthArr[1]}-${birthArr[2]}`).toDateString()
  return calculatedDay
}

console.log(getDay(birthDay))

CodePudding user response:

Your code is ok. I think you want like this format :

function convertDate(birthday) {

var usethisdate = new Date(birthday);

//let's start by finding the person's 65th birthday

var birthdaysixtyfive = new Date(usethisdate.setMonth(usethisdate.getMonth() 780));

    birthdaysixtyfive

    bd65 = (birthdaysixtyfive.getMonth()   1) '/' birthdaysixtyfive.getDate() '/' birthdaysixtyfive.getFullYear();
    
    console.log("65th birthday: ",bd65);
}


convertDate('11/15/1957');

Thanks.

CodePudding user response:

I would recommend using the 'momentjs' library. It has a function for difference.

const moment = require('moment')
function convertDate(birthday) {

    var usethisdate = new Date(birthday);
    
    //let's start by finding the person's 65th birthday
    
    var age  = moment().diff(usethisdate, 'years');
    console.log("Age: ",age);
    var currentDate = moment();
    var year = moment(currentDate).add(age, 'Y').format('DD-MM-YYYY'); //or replace age with 65
    console.log("Xth birthday: ",year);
    }

    convertDate(11/15/1957)
  • Related