javascriptangulartypescriptmomentjsangular-moment

Not getting time difference using MomentJS


Hey guys I'm trying get the difference of time using MomentJS so I can build a countdown clock. The problem is that I'm getting this error:

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]

My console.log is NaN

What am I doing wrong?

Here is the 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);
}


Solution

  • Firstly u need to take now inside to function , if not your end iss constant. then how can it count.

    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
    }
    

    call startTimer('11AM','2PM') in your html page