Maheswaran S
Maheswaran S

Reputation: 525

How to check two month are equal or not from date format YYYY-MM-DD?

I have two dates like 2020-12-31 and 2020-12-01 in string format yyyy-mm-dd while check the month it should return true.

Suppose I compare 2020-11-31 and 2020-12-31 it should return false.

If there is a difference in only month and year, it should return true.

For example today Feb 18, 2020, Suppose I choose Feb 11, 2020, it should return true, If I choose Jan 11, 2020, then it should return false.

Date difference should not be considered

Upvotes: 0

Views: 100

Answers (3)

Deep Kakkar
Deep Kakkar

Reputation: 6305

You can go with the following code:

const date1 = new Date('2020-12-01');
const date2 = new Date('2020-12-31');

// if you want to return true or false based on either date or month or year difference then use the following code.

const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
// this way if there is difference in either date or month or year then it will return true
if(diffDays) {
  return true;
} else {
  return false;
}

If you want to return either true or false on basis of either month or year only then you can use the following code.

const date1 = new Date('2020-12-01');
const date2 = new Date('2020-12-31');
// return basis on difference of either month OR year 
return date1.getMonth() === date2.getMonth() || date1.getYear() === date2.getYear()

// return basis on the difference of month AND year
return date1.getMonth() === date2.getMonth() && date1.getYear() === date2.getYear()

Upvotes: 1

Martynas Skučas
Martynas Skučas

Reputation: 528

Shorted, faster, and simpler solution is:

"2020-11-31".substr(5, 2) === "2020-12-31".substr(5, 2)

Upvotes: 0

ashu saini
ashu saini

Reputation: 86

@Maheshwaran You can use something like this

var d1 = new Date("2020-12-31")
var d2 = new Date("2020-12-31")
return d1.getMonth() === d2.getMonth() && d1.getYear() === d2.getYear()

Upvotes: 2

Related Questions