Home > Back-end >  How to compare/check two different date formats in javascript
How to compare/check two different date formats in javascript

Time:01-07

I would like to know how to compare any two different date strings in javascript.

Two Date Strings, d1 and d2 are always in the format , dd mmm yyyy and yyyy-mm-dd

How to compare datestring whether is same or not in javascript Below datestring is example,

var d1 = "12 Feb 1990" 
var d2 = "1990-02-12"

if(d1.split(' ').[1] === new Date().toLocaleString('en-US', {month: 'short'})){
  return true;
}
else {
return false
}


CodePudding user response:

Here's some code that reorders the "1990-02-12" string and compares it to the "12 Feb 1990" one:

function d2ToNormalDate(string) {
    return string.split("-")[1]   "-"   string.split("-")[2]   "-"   string.split("-")[0];
}
function areDateStringsEqual(string1, string2) { 
    // Expects string1 to be a string like "12 Feb 1990" and
    // expects string2 to be a string like "1990-02-12".
    // returns a boolean.
    return new Date(d2ToNormalDate(string2)).toString() === new Date(string1).toString()
}

CodePudding user response:

If you want to compare only the date string then the .toDateString method is all you need. Something like

const d1String = new Date(d1).toDateString()
const d2String = new Date(d2).toDateString()
if(d1String === d2String) {
   // do something if the two are equal
}else {
  // do something else if they are not equal
}

You can read more about the toDateString method on MDN

  •  Tags:  
  • Related