简体   繁体   English

使用date-fns的max函数从日期字符串数组中查找最大日期

[英]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: Dates字符串数组是从后端数据对象构造的,如下所示:

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" typeof(dates)是“对象”

How to find the get the latest date among the jsdates array? 如何在jsdates数组中查找获取最新日期?

Is it possible to apply max function of date-fns? 是否可以应用date-fns的max函数?

I can offer one solution, using the momentjs ( https://momentjs.com/ ) library. 我可以使用momentjs( https://momentjs.com/ )库提供一种解决方案。

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. 将每个对象转换为Date对象,并使用getTime()函数进行比较。

 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] ) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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