I am trying to compare updated date and time with current date and time. here i am getting one array of object there inside i have one updated at key. I need to find which object is near to current date and time and update another key inside that object.
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"
}
]
how to resolve this using map function
You can try:
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;
}
}
Note:
(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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.