Javascript 如何使用moment.js从日期列表中获取最小或最大日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46502405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get min or max dates from a list of dates using moment.js?
提问by Subhojit
I want to have the max date from the list of dates given in the handleClickfunction. How to find the max date from the list of dates using moment.js?
我想从handleClick函数中给出的日期列表中获得最大日期。如何使用moment.js从日期列表中找到最大日期?
I have the following code:
我有以下代码:
import React, {Component} from 'react';
import moment from 'moment';
class Getdate extends Component
{
constructor() {
super();
this.state = {
dates = []
}
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.state.dates = ['2017-11-12', '2017-10-22', '2015-01-10', '2018-01-01', '2014-10-10'];
console.log(this.state.dates);
}
render{
return (
<button onClick={this.handleClick}>Get Max Date</button>
)
}
}
export default Getdate
回答by Jimmy
You can use moment.maxfunction :
您可以使用moment.max函数:
let moments = this.state.dates.map(d => moment(d)),
maxDate = moment.max(moments)
回答by Luka
Sort them with a custom compartor, then select the first one (or last, try it out);
使用自定义比较器对它们进行排序,然后选择第一个(或最后一个,尝试一下);
array.sort(function(d1, d2) {
return moment(d1).isBefore(moment(d2));
});

