Search code examples
javascriptmomentjslodashluxon

Check if any date/time in array is greater then current local time using Luxon moment js


I am currently getting back 2 sets of times based of some json data. I want to be able to compare the current local time and check if its greater or less then any date in my json scheme.

const result = [
  {
    "carId": "13122656-169f-45fa-be47-26c9d23dcb7b",
    "carInstances": [
      {
        "carInstanceId": "47209558-f9e1-4f81-a600-5da6ce238a6e",
        "carTime": "2020-09-23T21:45:00.000+0000",
        "state": "COMPLETE",
      }
    ],
    "isPaused": false,
  },
  {
    "carId": "13122656-169f-45fa-be47-26c9d23dcb7b",
    "carInstances": [
      {
        "carInstanceId": "47209558-f9e1-4f81-a600-5da6ce238a6e",
        "carTime": "2020-09-23T21:45:00.000+0000",
        "state": "COMPLETE",
      }
    ],
    "isPaused": false,
  },
];

const timeAgo = (date) => {
    const now = DateTime.local();
    const past = DateTime.fromISO(date);
    const diff = past.diff(now, 'minutes');
    return Math.floor(diff.minutes);
}

const listCarTime = (res) => {
  return res.reduce((acc, car) => {
    acc.push(...car.carInstances.map((instance) => instance.carTime));
    return acc;  
  }, []);
}

console.log('result', timeAgo(results)); <----Returns NAN

Solution

  • You are passing result ( an array ) to timeAgo(date) function which expect iso format date and then ( as date parameter ) trying parse it what cant work. Your function work correctly when you pass correct argument.. you can try with proper iso date.

    timeAgo("2020-09-23T21:45:00.000+0000") // return 255017.36843333332
    
    const diffrences = result.map( res => res.carInstances.map( ins => timeAgo(ins.carTime) )).flat()
    
    console.log("result", diffrences )