0

Am displaying array of dates. I have to pick latest date out of date array. Please suggest how i can get the latest date.

class SearchResultsItem extends React.Component {
    render() {
        return (
            <tr onClick={ this.handleOpen } style={{fontsize: '10',cursor: 'pointer'}}>
                <td>{ this.props.item.number }</td>
                <td>{ this.props.item.name }</td>
                <td>{ this.props.item.buyer_name }</td>
                <td>{ this.props.item.order_date ? <Moment format="DD-MMM-YYYY">{ this.props.item.order_date }</Moment> : null }</td>
                </tr>

                <div className="col-sm-3">
                            <input name="date" disabled={ this.state.mode } type="date" value={ this.state.item.date } className="form-control" onChange={ this.handleInputChange } />
            </div>
        );
    }
Knut Herrmann
  • 30,880
  • 4
  • 31
  • 67
  • The latest date in which item? Comparing to what? Please provide more code and more information on what you want to achieve here. – DrunkDevKek Jul 28 '17 at 08:46
  • Please find the complete code., i have to get the latest date from the date array and place it in the field. –  Jul 28 '17 at 09:06
  • can you show us what date object looks like? – abdul Jul 28 '17 at 12:31
  • Date Object looks like this ---> 2017-09-02 (array of Date object ) stored in Mongodb as String type. –  Jul 28 '17 at 12:34

1 Answers1

0

Here is a solution you might want to try, what it basically does is just converts the given array of strings to date object and compare.

    var dates = ["2009-09-09", "2017-16-07", "2001-29-01"];
    var latest = dates[0];
    for(var i = 1; i < dates.length; i++) {
      if (formatToDate(dates[i]) > formatToDate(latest))
        latest = dates[i];
    }

   alert(latest);

    function formatToDate(dateString) {
      var d = new Date();
      dateString = dateString.split('-');
      d.setFullYear(dateString[0]);
      d.setMonth(dateString[1]);
      d.setDate(dateString[2]);
      return d;
    }

Orignal answer is here

abdul
  • 1,531
  • 1
  • 14
  • 29