我正试着为某人过生日,并找到他/她年满65岁的那一天。我有以下代码,但计算似乎不正确。例如,如果我使用1957年11月15日的生日,我应该将2022年11月5日作为65岁生日。然而,我得到的是1982年8月9日(这是不正确的(。
我是不是错过了什么?
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.toDateString());
}
convertDate('11/15/1957');
只需在提供的年份上加65即可。你会得到结果的。下面的代码应该可以完成工作。
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))
你的代码还可以。我想你想要这样的格式:
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');
谢谢。
我建议使用"momentjs"库。它具有差异的功能。
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)