Javascript is the best way to compare dates

I would like to collect all opinions on what is the correct way to sort dates in Javascript.

Check out the code snippets below, I have 2 scripts to sort dates using:

i) javascript date object
ii) custom javascript date string format

May I know why, when I sort by custom javascript date format, the display of the final results seems to be wrong compared to sorting using javascript date objects.

Should I sort the date using javascript date objects?

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>
      

Run codeHide result


+3


source to share


1 answer


Your problem is sortDateTime function. It skips the condition when a == b

and it compares strings and dates as if they were of the same type. Consider:



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));
      

Run codeHide result


0


source







All Articles