Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get min or max dates from a list of dates using moment.js?

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 
like image 443
Subhojit Avatar asked Sep 30 '17 11:09

Subhojit


People also ask

How do you compare dates in moments?

To compare two dates, just convert the dates to moment object and use the isSame() function. Compare if only day is the same. Check if months are equal. Check for year.

What is Moment () hour ()?

The moment(). hour() Method is used to get the hours from the current time or to set the hours. Syntax: moment().hour(); or. moment().

What is Moment () in Javascript?

Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.


1 Answers

You can use moment.max function :

let moments = this.state.dates.map(d => moment(d)),     maxDate = moment.max(moments) 
like image 61
Jimmy Avatar answered Sep 28 '22 16:09

Jimmy