Search code examples
javascriptmomentjsmoment-timezone

moment js 'from' giving weird result


I am getting the date from backend like this [2020, 8, 5, 13, 29, 43, 780000000] (this is UTC date).

I have to compare this date from current UTC to get the relative time. In this example current UTC was :- 2020-08-05T15:59:52.514Z

The expected relative time was 2h 30 mins. I am not sure why the actual response from Moment JS is 16 hrs.

const timeInUTC = moment.utc(date)
const currentTimeInUTC = moment.utc(new Date().toISOString())
console.log(timeInUTC.from(currentTimeInUTC))

enter image description here


Solution

  • The problem was in the format. The date which was input to moment was in array format, while I was calculating current time in UTC in "UTC format".

    After making sure both have the same format fixed the issue.

    const dateInUTCFormat = new Date(
            Date.UTC(date.value[0], date.value[1] - 1, date.value[2], date.value[3], date.value[4], date.value[5])
        )
    
        const timeInUTC = moment(dateInUTCFormat)
        const currentTimeInUTC = moment.utc()
        console.log(timeInUTC.from(currentTimeInUTC)
    

    )