0

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)

1
  • Yes, but strictly you should use localeCompare, e.g. date1 > date2 should be date1.localCompare(date2) > 0. Commented Feb 22, 2018 at 6:09

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I assumed that the date part was always sortable (been using it in filenames for years) but wasn't sure about the time part (and comparing mixed date and datetimes).
0

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

3 Comments

Ideally, I'd like to do this without converting to date objects.
I update without date object using string... may help
Far simpler to compare using String.prototype.localeCompare.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.