64

I want to have the max date from the list of dates given in the handleClick function. How to find the max date from the list of dates using 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
Subhojit
  • 1,389
  • 8
  • 19
  • 33

2 Answers2

130

You can use moment.max function :

let moments = this.state.dates.map(d => moment(d)),
    maxDate = moment.max(moments)
Jimmy
  • 2,669
  • 1
  • 17
  • 21
  • 4
    More concise is `this.state.dates.map( moment )` – Duncan Thacker Sep 30 '17 at 12:12
  • 11
    @DuncanThacker, no, don't use that concise form because it will send extra params to `moment` and result in a **parse error**. – Jimmy Sep 30 '17 at 12:20
  • @Jimmy why would it send extra params? `(d => moment(d))` and `(moment)` are equivalent. It's like doing `['abc','bcd'].map(x => console.log(x))` or `['abc','bcd'].map(console.log)` they are the same, aren't they? – Aquazi Apr 01 '19 at 09:28
  • 4
    @Aquazi The "extra params" I am referring to is the arguments of the `map` function. Here's a fiddle to showcase the error: https://jsfiddle.net/3qufbh5k/ The error is caused by the second `map(...)` argument, the index, which causes an error because `moment(...)` expects a string format as second parameter – Jimmy Apr 03 '19 at 02:58
  • 2
    **Beware** that if you happen to pass an empty list into `moment.max`, it erroneously returns the current date rather than something more reasonable like `undefined`. – Jemar Jones Feb 18 '20 at 20:27
  • @Jimmy how can I get max time only, from array of date-timestamp irrespective of date? – Faizan Saiyed Oct 15 '20 at 01:19
  • @FaizanSaiyed You can format by time to find the max: https://jsfiddle.net/IliasDeros/p2daxks1/18/ – Jimmy Oct 15 '20 at 14:11
-3

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));
        });
Luka
  • 435
  • 1
  • 7
  • 18
  • 3
    While this looks like it would work, note that `sort` expects _numeric_ return values from the compare function and not _boolean_. See [Sort array by date gives unexpected results](https://stackoverflow.com/questions/28013045/sort-array-by-date-gives-unexpected-results) – Boaz Sep 30 '17 at 11:58