我有一个元素数组,所有元素都具有DueDate属性。

但是,日期采用dd / MM / yyyy格式。

<div class="taskItem" dueDate="02/02/2016"></div>
<div class="taskItem" dueDate="20/02/2016"></div>
<div class="taskItem" dueDate="01/02/2016"></div>


当我进行以下排序时;

    $('.taskItem').sort(function (a, b) {
        var contentA = Date.parse($(a).attr('dueDate'));
        var contentB = Date.parse($(b).attr('dueDate'));
        console.log(contentA)
        return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
    })


我在看起来像2016年2月20日的日期时出错。 2016年2月20日。dd/ MM / yyyy

最佳答案

将排序方法更改为demo

    function toDate(value)
    {
       var from = value.split(" ")[0].split("/");
       return (new Date(from[2], from[1] - 1, from[0]));
    }
    $('.taskItem').sort(function (a, b) {
        var contentA = toDate($(a).attr('dueDate')).getTime(); //assuming that attribute value will always be a valid date
        var contentB = toDate($(b).attr('dueDate')).getTime();
        console.log(contentA);
        return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
    });


比较时间(以毫秒为单位),而不是整个日期字符串

10-06 11:54