简体   繁体   中英

Sort date strings javascript

I have datetimes and dates stored as strings in javscript that I need to compare.

Leaving them as strings seems to work:

const date1 = '2016-01-26 05:20:44'
const date2 = '2016-01-26 06:20:44'
const date3 = '2016-02-26'

date1 > date2 //false
date1 < date2 //true
date3 > date2 //true
date3 > date1 //true
date1 > date3 //false

The question: can I depend on this? Or is this a "it works, but it's not reliable" kind of deal?

Should I convert the date strings into date objects (using date or moment )

If that is your format, it should continue to work. Think about it: one of the major advantages of that format is exactly that it's sortable.

Of course Date objects themselves are also sortable. The internal valueOf method used in comparing them returns milliseconds since a fixed time.

Updated.....

function removeAllNoNumber(a) {
   return  a.toString().replace(/\D/g, '');
}

function padRight(source, padChar, padCount) {
  var dif = padCount - source.toString().length;
  if (dif <= 0) {
     return source;
  } else {
     var c = "";
     for (var i = 0; i < dif; i++) {
         c += padChar.toString();
     }
         return (source + c);
     }
}

function timeToInt(a){
     return parseInt(padRight(removeAllNoNumber(a),"0",14),10);
}


  var date1 = timeToInt("2016-01-26 05:20:44"); //20160126052044 
  var date2 = timeToInt("2016-01-26 06:20:44"); //20160126062044
  var date3 = timeToInt("2016-01-26"); //20160126000000

   if (date1 < date2) {

     alert("here");
   }

Like this you can take extract the date from your given strings in the problem if the format never changes by using substring()

date1.substring(0,10)
date2.substring(0,10)
date3.substring(0,10)

output to substring

"2016-01-26"

"2016-01-26"

"2016-02-26"

and now you can compare the extracted substrings of dates by comparing them like

date1.substring(0,10) > date1.substring(0,10) //false

It is little messy but it will keep you main string unchanged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM