js如何计算两个日期之间间隔了多少天？

5 个回答
✓ 已被采纳
``````this.startDate = this.\$moment(this.form.date_time[0]).format('YYYY-MM-DD')
this.endDate = this.\$moment(this.form.date_time[1]).format('YYYY-MM-DD')
const sDate = Date.parse(this.startDate)
const eDate = Date.parse(this.endDate)
const days = (eDate - sDate) / (1 * 24 * 60 * 60 * 1000) //间隔时间``````

``````const a = Date.parse("2022-11-28");
const b = Date.parse("2022-11-29");
// 相隔多少天的结果, 没满一天按一天算，如果不满的ceil换成floor
const d1 = Math.ceil(Math.abs(b - a) / 86400000);``````

「嘿嘿：我这不需要精确到时分秒」

``````data() {
return {
starttime: `2018/12/27 00:00:00`
}
},
methods: {
timeInterval() {
this.timer = setInterval(() => {
// console.log(this.intervalTime);
const start = moment(this.starttime).valueOf();
const current = moment().valueOf();
const time = parseInt((current - start)/1000/60/60/24) // 天
const time1 = parseInt((current - start)/1000/3600) // 时
const time2 = parseInt((current - start)/1000/60) // 分
const time3 = parseInt((current - start)/1000) // 秒
const result = `\${time}天\${time1 - time*24}时\${time2 - time1*60}分\${time3 - time2*60}秒`;
this.intervalTime = result;
}, 1000);
}
}``````

``````const diffDays = (d1, d2) => (d1 - d2) / (1000 * 60 * 60 * 24);
// diffDays(new Date('2022-12-12 10:10:10'), new Date('2022-10-10 12:12:10')).toFixed(2)``````

你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进