Estoy tratando de comparar la fecha y la hora actualizadas con la fecha y la hora actuales. aquí obtengo una matriz de objetos allí dentro, tengo uno actualizado en key. Necesito encontrar qué objeto está cerca de la fecha y hora actuales y actualizar otra clave dentro de ese objeto.
for(var i =0;i<data.length;i++){ if(data[i].updated_at > data[i+1].updated_at ){ data.is_latest="true" } } // below is my data [ { "is_latest": "", "created_at": "2021-09-21T21:24:05.000Z", "updated_at": "2021-09-21T17:53:29.000Z" }, { "is_latest": "", "created_at": "2021-09-29T21:24:05.000Z", "updated_at": "2021-09-29T17:53:29.000Z" } ] // in the above i am getting data here how to find updated_at nearer to current date and time using moment.js [ { "is_latest": "", "created_at": "2021-09-21T21:24:05.000Z", "updated_at": "2021-09-21T17:53:29.000Z" }, { "is_latest": true, "created_at": "2021-09-29T21:24:05.000Z", "updated_at": "2021-09-29T17:53:29.000Z" } ]cómo resolver esto usando la función de mapa
Puedes probar:
let today = Date.now(); let latest_index = 0, latest_diff = today - (new Date(data[0].updated_at)).getTime(); for(let i=1;i<data.length; i++){ let updated_date = (new Date(data[i].updated_at)).getTime(); if (today - updated_date < latest_diff){ latest_index = i; latest_diff = today - updated_date; } }Nota:
(new Date()).getTime; // This will return you the number of milliseconds elapsed from January 1, 1970 // if your date is less than that date, the value will be negative