-2

I have a collection like this:

[
{X:1, Date:"12/01/2017 12:30am"},
{X:3, Date:"12/01/2017 1am"},
{X:2, Date:"12/01/2017 3am"}
]

What Javascript/Typescript can I use to calculate the elapsed time based on the items in the set?

reeversedev
  • 382
  • 1
  • 3
  • 18
user8570495
  • 1,645
  • 5
  • 19
  • 29
  • expected result based on your sample ? – klugjo Dec 20 '17 at 08:18
  • 150 minutes.... – user8570495 Dec 20 '17 at 08:20
  • Will the dates always be in that format? If you can use a better format it will be much easier to convert them into date objects – user184994 Dec 20 '17 at 08:40
  • the datetimes will actually be in the following format: "2017-12-20 08:48:54" – user8570495 Dec 20 '17 at 08:50
  • I would iterate over the object array, pluck the date values into a simple array (dateArray) and use Math.min.apply(null, dateArray) and Math.max.apply(null, dateArray) to find the min Date and the max Date and then subtract the two. Or look at something like moment.js to coerce them into uniform date objects, and see if there's a utility method there to return a duration. – Stephen R. Smith Dec 20 '17 at 09:09

2 Answers2

0

For your input like this

arr =[
{X:1, date:"2017-12-20 08:48:54"},
{X:3, date:"2017-12-20 09:48:54"},
{X:2, date:"2017-12-20 12:48:54"}
]

you can use

var elapsedTime = [];
for (var i =0; i< arr.length-1; i++) {
    elapsedTime.push((new Date(arr[i+1].date) - new Date(arr[i].date))/(1000*60));
}

Here you are converting the value to date format and then subtracting which give you the difference in milliseconds.

To calculate the difference use this -

var diff = Math.max(...elapsedTime) - Math.min(...elapsedTime)
Eftakhar
  • 455
  • 4
  • 17
  • thanks @eftakhar. I think you're on the right track but your code returns an array of [60,180] but I need a single number which represents the difference between the min and the max. so II'm looking for a single result of 240 for the example you provided above. the solution code also should not depend on a sequential ordering of the objects by date. – user8570495 Dec 20 '17 at 10:34
  • you should have mentioned that in your question initially itself. Anyways updated the answer for you need. – Eftakhar Dec 25 '17 at 18:21
0

Map your array to an array of timestamps, apply the mapped array to Math.max and Math.min, subtract, and convert to your unit of choice.

AuxTaco
  • 4,883
  • 1
  • 12
  • 27