68

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
0

2 Answers 2

136

You can use moment.max function :

let moments = this.state.dates.map(d => moment(d)),
    maxDate = moment.max(moments)
Sign up to request clarification or add additional context in comments.

7 Comments

More concise is this.state.dates.map( moment )
@DuncanThacker, no, don't use that concise form because it will send extra params to moment and result in a parse error.
@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 The "extra params" I am referring to is the arguments of the map function. Here's a fiddle to showcase the error: 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
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.
|
-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));
        });

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.