Reputation: 1381
I have an array of dates and wanted to find the max and min dates in an array.
This is my code:
let date_list = [
"2021-03-19T00:00:00Z",
"2021-03-20T00:00:00Z",
"2021-04-12T00:00:00Z",
"2021-04-13T00:00:00Z",
"2021-04-11T00:00:00Z",
"2021-04-12T00:00:00Z",
"2021-03-18T00:00:00Z"
];
let uniq_dates = [...new Set(date_list.map(d => moment.utc(d).format() ))];
console.log(uniq_dates);
console.log(moment().max(date_list));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>
I sometimes get an error that says NaN
or I am getting Deprecation warning: moment().max is deprecated, use moment.min instead.
How do I get max and min in an array of dates?
Upvotes: 0
Views: 1694
Reputation: 2121
You can use this code.
let date_list = [
"2021-03-19T00:00:00Z",
"2021-03-20T00:00:00Z",
"2021-04-12T00:00:00Z",
"2021-04-13T00:00:00Z",
"2021-04-11T00:00:00Z",
"2021-04-12T00:00:00Z",
"2021-03-18T00:00:00Z"
];
let moments = date_list.map(d => moment(d)),
maxDate = moment.max(moments)
console.log(maxDate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>
Upvotes: 1
Reputation: 89139
You can use Array#reduce
in conjunction with moment.max
.
let date_list = [
"2021-03-19T00:00:00Z",
"2021-03-20T00:00:00Z",
"2021-04-12T00:00:00Z",
"2021-04-13T00:00:00Z",
"2021-04-11T00:00:00Z",
"2021-04-12T00:00:00Z",
"2021-03-18T00:00:00Z"
];
let uniq_dates = [...new Set(date_list.map(d => moment.utc(d).format() ))];
console.log(uniq_dates);
console.log(uniq_dates.reduce((acc,curr)=>acc.max(curr), moment()));
.as-console-wrapper{max-height:100%!important;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>
Upvotes: 1