没有使用 MomentJS 获得时差

Not getting time difference using MomentJS

大家好,我正在尝试使用 MomentJS 来计算时差,这样我就可以构建一个倒计时时钟。 问题是我收到此错误:

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info. Arguments: [0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 00:00, _f: undefined, _strict: undefined, _locale: [object Object]

我的console.log是NaN

我做错了什么?

这是TS:

now: any;

ngOnInit() {
     this.now = parseInt(moment().format('h'));
}
///
startTimer() {
    const endTime = moment('10AM', ['h:mm A']).format('HH:mm');
    const a = moment(this.now, 'HHmm').diff(endTime, 'hours');
    console.log(a);
}

首先,你需要将 now 带入内部才能发挥作用,否则你的结局是不变的。那怎么算呢。

startTimer(from,to){
    const now = moment(from, ['h:mm A']).format('H:mm:ss')
    const end = moment(to, ['h:mm A']).format('H:mm:ss');
    var a ;
    if(now>end){
            a = moment.utc(moment(now,['H:mm']).diff(moment(end,['H:mm']))).format("H:mm");
    }
    else{
          a ="-"+ moment.utc(moment(end,['H:mm']).diff(moment(now,['H:mm']))).format("H:mm");
    }
    return a
}

在您的 html 页面中调用 startTimer('11AM','2PM')

像这样使用减法而不是差异:

const endTime = moment('10:00 AM', ['h:mm A']).format('HH:mm');
const a = moment(moment(this.now, 'h:mm A').subtract(endTime, 'hours')).format('hh');
console.log(a);