how can I compare dates in array to find the earliest one?

前端 未结 5 1642
故里飘歌
故里飘歌 2021-01-21 00:41

I have a variable called dateArray with dates in it for example

[\"09/09/2009\", \"16/07/2010\", \"29/01/2001\"]

and I want to find the earlies

5条回答
  •  孤城傲影
    2021-01-21 01:08

    Sometimes the most basic approach is the best:

    var dates = ["09/09/2009", "16/07/2010", "29/01/2001"];
    var min = dates[0];
    for(var i = 1; i < dates.length; i++) {
      if (fDate(dates[i]) < fDate(min))
        min = dates[i];
    }
    
    alert(min);
    
    // create a proper Date object from the string
    function fDate(s) {
      var d = new Date();
      s = s.split('/');
      d.setFullYear(s[2]);
      d.setMonth(s[1]);
      d.setDate(s[0]);
      return d;
    }

    The code I wrote for you above converts each string into a Date object, and then finds the minimum (the earliest date) from them. No string hacks, just straightforward date comparison. It returns the original string from the array.

提交回复
热议问题