Search code examples
javascriptdategetmomentjsunix-timestamp

MomentJS Parsing Unix Timestamp Sent Through GET Request Incorrectly


I have an array of 2 strings, both of which are in Unix time.

[1484930449590,1548002449590]

Converting these back into human readable time gives me today's date and the date 2 years ago.

However, when I parse both of these timestamps with MomentJS:

const start = moment(timeRange[0])
const end = moment(timeRange[1])

I receive the following values:

moment("2001-01-01T00:00:00.000")
moment("2001-04-01T00:00:00.000")

For some reason, momentJS converts both of the timestamps to the year 2001, even though the years should be 2019 and 2017.

Parsing the strings first does not make things better:

const start = moment(parseInt(timeRange[0]))
const end = moment(parseInt(timeRange[1]))

Now start and end are:

moment("1969-12-31T19:00:00.001")
moment("1969-12-31T19:00:00.004")

Does anyone know what is going on?

I tried the following solution:

console.log(timeRange)
const start = moment(parseInt(timeRange[0]) / 1000)
console.log(start)
const end = moment(parseInt(timeRange[1]) / 1000)
console.log(end)

but nothing changed:

1484931697215,1548003697215
moment("1969-12-31T19:00:00.000")
moment("1969-12-31T19:00:00.000")

Update:

The issue is that I was wrong about timeRange being an array. Rather, it was actually a string. This happened because on the client-side timeRange was an array, but when it got sent as a GET request to the server and retrieved with const timeRange = req.query.timeRange, it got converted to a string.


Solution

  • The issue is that I was wrong about timeRange being an array. Rather, it was actually a string. This happened because on the client-side timeRange was an array, but when it got sent as part of a GET request to the server and retrieved with const timeRange = req.query.timeRange, it got converted to a string.

    The solution was to reconvert the timeRange back into an array:

    const times = req.query.timeRange.split(",")
    const startDate = moment(parseInt(times[0]))
    const endDate = moment(parseInt(times[1]))