【问题标题】:Javascript - Best Way to Compare DatesJavascript - 比较日期的最佳方式
【发布时间】:2017-10-30 08:41:53
【问题描述】:

我想收集大家对在 Javascript 中对日期进行排序的正确方法的意见。

查看下面的代码 sn-ps,我有 2 个场景可以使用:

i) javascript 日期对象
ii) 自定义 javascript 日期字符串格式

我可以知道为什么当我按自定义 javascript 日期格式排序时,与使用 javascript 日期对象的排序相比,最终结果显示似乎是错误的。

我应该使用 javascript 日期对象对日期进行排序吗?

Date.prototype.getDateFormat = function (value) {
        var d = this.getDate();
        if (d < 10)
            d = "0" + d;

        var month = this.getMonth() + 1;
        if (month < 10)
            month = "0" + month;

        return value.replace("MM", month).replace("dd", d).replace("yyyy", this.getFullYear());
}

Date.prototype.getTimeFormat = function (value) {
        var h = this.getHours();
        var m = this.getMinutes();
        var s = this.getSeconds();
        var a = "AM";

        if (h == 12) {
            a = "PM";
        } else if (h > 12) {
            a = "PM";
            h = h - 12;
        }
        if (h < 10) {
            h = "0" + h;
        }
        if (m < 10) {
            m = "0" + m;
        }
        if (s < 10) {
            s = "0" + s;
        }
        return value.replace("hh", h).replace("mm", m).replace("ss", s).replace("tt", a);
}

function sortDateTime(a,b){
	if(a > b) return 1;
  else if(a < a) return -1;
}

var dateList1 = [];
var dateList2 = [];

// Using pure Javascript Date Object
var date1 = new Date("06/03/2017 12:00:00 PM");
var date2 = new Date("06/03/2017 03:00:00 PM");
var date3 = new Date("06/03/2017 05:00:00 PM");

dateList1.push(date1);
dateList1.push(date2);
dateList1.push(date3);

var result1 = dateList1.sort(sortDateTime);

for(var e = 0 ; e < result1.length ; e++){
  var display = "<div>" + result1[e] + "</div>";
  $("#result1").append(display);
}
//Result from result1 List
// 1) 06/03/2017 12:00:00 PM
// 2) 06/03/2017 03:00:00 PM 
// 3) 06/03/2017 05:00:00 PM

// Using Javascript Date Time custom string format
var pDate1 = new Date("06/03/2017 12:00:00 PM");
var pDate2 = new Date("06/03/2017 03:00:00 PM");
var pDate3 = new Date("06/03/2017 05:00:00 PM");

var rDate1 = pDate1.getDateFormat("yyyyMMdd") + pDate1.getTimeFormat(" tt hhmmss");
var rDate2 = pDate2.getDateFormat("yyyyMMdd") + pDate2.getTimeFormat(" tt hhmmss");
var rDate3 = pDate3.getDateFormat("yyyyMMdd") + pDate3.getTimeFormat(" tt hhmmss");

dateList2.push(rDate1);
dateList2.push(rDate2);
dateList2.push(rDate3);

var result2 = dateList2.sort(sortDateTime);

for(var e = 0 ; e < result2.length ; e++){
  var display = "<div>" + result2[e] + "</div>";
  $("#result2").append(display);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b> Sort by Javascript Date object</b>
<div id="result1"></div>
<br/>
<b> Sort by Javascript Custom Date Time string Format</b>
<div id="result2"></div>

【问题讨论】:

  • 缺少sortDateTime 函数if (a == b) return 0(或仅使用return a - b)。你不应该依赖内置解析,不要做new Date("06/03/2017 12:00:00 PM")。比较字符串时,sortDateTime 应使用a.localeCompare(b)(参见MDN)。
  • 对于基于字符串的时间比较,您需要使用 24 小时制,以便将“12:30 PM”和“01:00 PM”作为“12:30”和“13”进行比较:00”。顺便说一句,“我想收集大家的意见”一般不是appropriate for for StackOverflow

标签: javascript sorting datetime


【解决方案1】:

您的问题是 sortDateTime 函数。它缺少a == b 的条件,并且它正在比较字符串和日期,就好像它们是同一类型一样。考虑:

function sortDateTime(a, b) {

  // If strings, compare as strings
  if (typeof a == 'string') {
    return a.localeCompare(b);
  }

  // Otherwise, compare as numbers
  return a - b;
}


var data = ['2017-03-06T12:00:00','2017-03-06T03:00:00','2017-03-06T17:00:00'];

// Copy and sort as strings
// The strings should be parsed as local, but Safari will parse them as UTC
// They'll be sorted in the same order, they'll just be offset by the host offset
var x = data.slice();
console.log(x.sort(sortDateTime));

// Copy and convert to Dates, then sort
var y = data.map(function(s){return new Date(s)});
console.log(y.sort(sortDateTime));

【讨论】:

    猜你喜欢
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多