排序字符串日期数组 [英] Sort a string date array

查看:236
本文介绍了排序字符串日期数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按升序对数组进行排序。日期是字符串格式

I want to sort an array in ascending order. The dates are in string format

["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"] 

甚至需要一个功能来检查这些日期是否是连续的:

Even need a function to check whether these dates are in continuous form:

eg - Valid   - ["09/06/2015", "10/06/2015", "11/06/2015"] 
     Invalid - ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015"] 

示例代码:

function sequentialDates(dates){
        var temp_date_array = [];

        $.each(dates, function( index, date ) {
            //var date_flag = Date.parse(date);
            temp_date_array.push(date);
        });

        console.log(temp_date_array);

        var last;
        for (var i = 0, l = temp_date_array.length; i < l; i++) {

          var cur = new Date();
          cur.setTime(temp_date_array[i]);
          last = last || cur;
          //console.log(last+' '+cur);

          if (isNewSequence(cur, last)) {
            console.log("Not Sequence");
          }
        }

        //return dates;
    }

     function isNewSequence(a, b) {
          if (a - b > (24 * 60 * 60 * 1000))
              return true;
          return false;
      }


推荐答案

简单解决方案



没有必要将字符串转换为日期或使用RegExp。

The Simple Solution

There is no need to convert Strings to Dates or use RegExp.

简单的解决方案是使用Array.sort()方法。排序函数将日期格式设置为YYYYMMDD,然后比较字符串值。假设日期输入格式为DD / MM / YYYY。

The simple solution is to use the Array.sort() method. The sort function sets the date format to YYYYMMDD and then compares the string value. Assumes date input is in format DD/MM/YYYY.

data.sort(function(a,b) {
  a = a.split('/').reverse().join('');
  b = b.split('/').reverse().join('');
  return a > b ? 1 : a < b ? -1 : 0;
});

运行Snippet进行测试

<!doctype html>
<html>
<body style="font-family: monospace">
<ol id="stdout"></ol>
<script>
  var data = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];

data.sort(function(a,b) {
  a = a.split('/').reverse().join('');
  b = b.split('/').reverse().join('');
  return a > b ? 1 : a < b ? -1 : 0;
});

for(var i=0; i<data.length; i++) 
  stdout.innerHTML += '<li>' + data[i];
</script>
</body>
</html>

这篇关于排序字符串日期数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆