简体   繁体   中英

Find max date from a string array of dates using max function of date-fns

Dates string array is constructed from backend data object as below:

const dates: string[] = this.data.map((item:any) => item.date.jsdate);

The result is

dates = [
    Thu Jan 12 2015 00:00:00 GMT+0530 (India Time), 
    Tue Feb 25 2015 00:00:00 GMT+0530 (India Time), 
    Sun Jan 28 2016 00:00:00 GMT+0530 (India Time)
]

typeof(dates) is "object"

How to find the get the latest date among the jsdates array?

Is it possible to apply max function of date-fns?

I can offer one solution, using the momentjs ( https://momentjs.com/ ) library.

You can sort the dates using:

dates = dates.sort((a,b) => moment(a).diff(moment(b));

Then if you want the latest date you could take the last element from that array:

return dates[dates.length-1];

You should also be able to do this without moment:

dates = dates.sort((a,b) => new Date(b) - new Date(a));

Convert each to a Date object and compare using getTime() function.

 var dates = [ 'Thu Jan 12 2015 00:00:00 GMT+0530 (India Time)', 'Tue Feb 25 2015 00:00:00 GMT+0530 (India Time)', 'Sun Jan 28 2016 00:00:00 GMT+0530 (India Time)' ] console.log( dates.sort((a,b)=>new Date(b).getTime() - new Date(a).getTime())[0] ) 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM