gpt4 book ai didi

JavaScript Moment.js 试图获得 2 个日期时间之间的差异

转载 作者:行者123 更新时间:2023-11-30 20:17:20 25 4
gpt4 key购买 nike

我试图找出 2 个日期时间戳之间的区别,它们看起来像这些:

2018-08-22 00:00:00 
2018-08-11 15:34:31

我想显示以天为单位的时差 - 小时 - 分钟 - 剩余秒数。

到目前为止,我这样做了,但它总是返回 NaN:

import moment from 'moment';

const calc = {

render () {
moment().format();
this.calcDifference();
},

calcDifference() {
let releaseDate = document.getElementById('release-at').value;
let currentDate = document.getElementById('current-date').value;

let ms = moment(
releaseDate,
"DD-MM-YYYY HH:mm:ss").diff(moment(currentDate,
"DD-MM-YYYY HH:mm:ss")
);
let d = moment.duration(ms);
let s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");

console.log(ms);
console.log(d);
console.log(s);
}

};

calc.render();

最佳答案

在您的calcDifference 函数上,您可以这样做

let releaseDate = moment('2018-09-22 00:00:00');
let currentDate = moment('2018-08-11 15:34:31');

const diff = releaseDate.diff(currentDate);
const diffDuration = moment.duration(diff);

console.log(`
${diffDuration.months()} months
${diffDuration.days()} days
${diffDuration.hours()} hours
${diffDuration.minutes()} minutes
${diffDuration.seconds()} seconds left!`);

如果 release-atcurrent-date 元素的值有格式DD-MM-YYYY HH:mm:ss,使用

let releaseDate = moment(document.getElementById('release-at').value, 'DD-MM-YYYY HH:mm:ss');
let currentDate = moment(document.getElementById('current-date').value, 'DD-MM-YYYY HH:mm:ss');

这是一个有效的 codepen

希望对您有所帮助! :)

关于JavaScript Moment.js 试图获得 2 个日期时间之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51801248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com