Convert array of timestamps with Date javascript

I have an array of timestamps and I want to transform it into dates.

timestamps = [1568666854141, 1568595225048, 1568594645595];
timestamps.forEach(function(d) { d = new Date(d) } )

When I do new Date(d) in debug it gives me Mon Sep 16 2019 16:47:34 GMT-0400 which is good, but if I check my array, it's still the same. It gives me [1568666854141, 1568595225048, 1568594645595] instead of [Mon Sep 16 2019 16:47:34 GMT-0400, ...] Why does not every element d reassigns to a date?

Upvotes: 0

Views: 1978

Answers (3)

沈鑫Real
沈鑫Real

Reputation: 31

forEach can not modify the orgin array, please use map:

let timestamps = [1568666854141, 1568595225048, 1568594645595];
timestamps = timestamps.map(function(d) { return new Date(d) } )

Upvotes: 3

I solved my problem doing this:

timestamps.forEach(function(elem, idx, arr) {arr[idx] = new Date(elem); });

Upvotes: 0

j6m8
j6m8

Reputation: 2399

You're creating a new array and creating a new (correct) date value for each element, but not doing anything with the values.

timestamps = timestamps.map(function(d) { return new Date(d) } );

Upvotes: 1

Related Questions