1

I've got some behavior I don't understand when I'm trying to take my input array of milliseconds and change them to dates with Date(). For example:

0: 1582641000
1: 1582727400
2: 1582813800
3: 1582900200
4: 1583159400
5: 1583245800
6: 1583332200
7: 1583418600
8: 1583505000
9: 1583760600
10: 1583847000

So far I've used pretty simple functions to do this, like:

for (i = 0; i < timestamp.length; i++) {
    timestamp[i] = Date(timestamp[i]);
}

Strangely, to me at least, this makes every element of "timestamp" the same date value. Similarly, if I do:

for (i = 0; i < timestamp.length; i++) {
    timestamp[i] = new Date(timestamp[i]);
}

Now every date in the "timestamp" array is in Jan 19 1970. What's going on here? How can I get the correct human readable string array from this? I.E.: Mar 25 2020 20:50:00 GMT-0700 (PDT)?

2
  • 1
    First multiply with 1000 to convert UNIX timestame in seconds to convert into milliseconds and then use toLocaleDateString("en-US") to convert it into date-time format. So you can do like this `` timestamp[i] = new Date(timestamp[i] * 1000).toLocaleDateString("en-US");`` Commented Mar 26, 2020 at 3:57
  • How I didn't notice to my data was in seconds and not milliseconds is beyond me... Commented Mar 26, 2020 at 18:01

1 Answer 1

2

The Date constructor accepts milliseconds as a single parameter, not seconds. Multiply the number by 1000 first.

You also must use new, otherwise the resulting date string will be at the current time, not the timestamp of the parameter. (All arguments are ignored without new)

Use .map instead of a for loop, and call toUTCString:

const arr = [
  1582641000,
  1582727400,
  1582813800,
  1582900200,
  1583159400,
  1583245800,
  1583332200,
  1583418600,
  1583505000,
  1583760600,
  1583847000,
];
const arrOfDates = arr.map(secs => new Date(secs * 1000).toUTCString());
console.log(arrOfDates);

Sign up to request clarification or add additional context in comments.

1 Comment

How I didn't notice to my data was in seconds and not milliseconds is beyond me...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.