Home > Enterprise >  How can I shift in time an array of timestamps in javascript?
How can I shift in time an array of timestamps in javascript?

Time:03-17

I have an array of time objects created like this:

let event = new Date()

These events are created overtime, for example:

  • first event created*
  • 2 seconds later another event created
  • 5 seconds later another event
  • 3 seconds later another is created etc...

So each time object has the corresponding time at which it was created.

The events where obviously created in the past, and there is afirst event.

and they are all stored in an array like: [event1, event2, event3...] The events are the object the function new Date() returns.

How can I shift all these events so that they start in the future?

By the future I mean for example whenever an event is executed, a click etc...

How can i shift their time equally to that all events go in the same order, but start in the future.

Is like a recording, being played back.

Thanks

CodePudding user response:

var events = [...];
    
var firstEvent = events[0];
var now = new Date();
var oldestEventAge = now.getTime() - firstEvent.getTime();

var hour = 1000 * 60 * 60;
for (let e of events) {
    e.setTime(e.getTime()   oldestEventAge   hour);
}

Here we get the first event and calculate how many milliseconds have occurred between now and it. i.e. how old is it.

Then we define 1 hour in milliseconds. This is how far we are pushing the first event into the future.

Then for each event we add to its current time in milliseconds the age of the oldest event plus one hour.

This will result in the oldest event being 1 hour in the future and all subsequent events being the same distance from the oldest event and also in the future.

Obviously change the value of hour to be however far you want the first event to be in the future.

CodePudding user response:

While Date handling is one of the pretty bad parts of JS1, this short of shifting is relatively simple. We just calculate new timestamps based on the difference between the first date in the list and the current one, and add that difference to our new start time, then create a Date from that timestamp:

const shiftEvents = (start, events) =>
  events .map (e => new Date (e - events[0]   start .getTime ()))

const events = [new Date ('2022-03-09T22:51:03.507'), new Date ('2022-03-09T22:51:05.492'), new Date ('2022-03-09T22:51:10.604'), new Date ('2022-03-09T22:51:13.551')]

console .log (shiftEvents (new Date ('2022-03-16T22:59:18.219'), events))


1 There is something better on the horizon in the Temporal proposal.

  • Related