Reputation: 55
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)?
Upvotes: 1
Views: 464
Reputation: 370619
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);
Upvotes: 2