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
}
If you want to compare only the date string then the .toDateString method is all you need. Something like
You can read more about the toDateString method on MDN
let d1 = "12 Feb 1990"
let d2 = "1990-02-12"
const d1String = new Date(d1).toDateString()
const d2String = new Date(d2).toDateString()
if (d1String === d2String) {
console.log('Equal');
} else {
console.log('Not equal');
}
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()
}