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

时间:2018-08-11 15:37:59

标签: javascript date datetime momentjs ticker

我正在尝试获得两个看起来像这样的日期时间戳之间的差异:

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();

1 个答案:

答案 0 :(得分:1)

在您的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!`);

如果发布日期当前日期元素中的值具有格式 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

希望对您有所帮助! :)