使用JavaScript添加两个不同的日期



大家好,

我正在尝试执行以下

1-从用户选择的日历中获取值。2-将所选值加上五年。3-从当前日期减去值+五年。4显示的结果(值+5年-当前日期(。

到目前为止,这就是我所尝试的,以毫秒为单位的结果不会被正确添加——这有点像是将两个字符串相互添加,我不想这样做

let selectDate = document.getElementById('Calender').value;
let exact = Date.parse(selectDate);
let fiveYearsInMs = "157784760000";
console.log(exact+fiveYearsInMs);

Ps:我希望只使用JavaScript,不使用moment.js或任何其他

有什么需要帮忙的吗?

这里有一种在日期上添加5年的方法。此方法要求输入日期为可识别的格式,例如来自日期选择器或数据库中的日期字段。它将传入的字符串转换为日期格式,然后我们重建日期字符串,在年份上加5。

let fiveYears = 
(d.getFullYear() + 5) + "-" +  // we get the year and add 5
("0" + (d.getMonth() + 1)).slice(-2) +"-"+  // we get the month (which is zero based so we need to add 1 - then we pad it with a leading zero and finally take the last 2 via slice()
("0" + d.getDate()).slice(-2); // we get the day and pad as mentioned above

document.querySelector('input').addEventListener('change', (e) => {
doDate(e.target.value)
})
// this next function relies on the selectDate being a recognizable date format, which it definitely will be if it comes from a date text element like this example
const doDate = (selectDate) => {
//let selectDate = document.getElementById('Calender').value;
let d = new Date(selectDate)
let fiveYears = 
(d.getFullYear() + 5) + "-" +  
("0" + (d.getMonth() + 1)).slice(-2) +"-"+ 
("0" + d.getDate()).slice(-2);

console.log(fiveYears) // date string
console.log(new Date(fiveYears)) // date Object
console.log(new Date(fiveYears).getTime()); //milliseconds
}
// Archived: the following line (commented out) is not a reliable way to get the date, even though it will work for most modern browsers today, it's platform and browser dependent. 
// I am leaving it here for posterity since this is how the answer was accepted
// let fiveYears = selectDate.split("-").map((e, i) => i == 0 ? +e + 5 : e).join("/");
<input type='date' />

你很接近!但只需要将fiveYearsInMs作为一个整数,而不是字符串。

let selectDate = "2021-06-13"
let exact = Date.parse(selectDate);
let fiveYearsInMs = 157784760000;
console.log(exact + fiveYearsInMs);
let futureDate = new Date(exact + fiveYearsInMs)
console.log(futureDate)

相关内容

  • 没有找到相关文章

最新更新