Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a day is the same day (but not year) with momentjs

Tags:

momentjs

I'm using momentjs to determine wether or not a date is a persons birthday. But for some reason moment always returns false and I'm not sure why.

Used code

moment(dateObject).isSame(moment(otherDateObject), 'day')

What is returned when logging the individual dates and the isSame()

enter image description here

Any ideas on what the issue is here? As you can see the only difference in the 2 moment instances is the year.

From momentjs

Passing in day will check day, month, and year

So how do I check if it is the matching day and month then?

like image 884
NealVDV Avatar asked May 23 '17 08:05

NealVDV


People also ask

How do I compare two dates in Momentjs?

Compare two dates using Moment. js has a diff() method, which gives the difference between two dates in years, months, days, hours, minutes, seconds, milliseconds, etc. We can use the second unit in our case to find the difference between the two dates. Before using the Moment. js methods, make sure to include Moment.

How do I get today's date in Momentjs?

moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format.

What can I use instead of Momentjs?

And today, the most popular alternative to Moment. js is Day. js which surpassed date-fns on GitHub by stars (46,2k Day. js stars vs 37,7k date-fns stars).

How do you know if a date is future in moment?

How do you find the future date in the moment? var travelTime = moment(). add(642, 'seconds'). format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format.


1 Answers

If you want to check only day of the month and the month, you can write your own function using date() and month() getters.

Here a sample:

var m1 = moment('2017-01-25');
var m2 = moment('2015-02-25');
var m3 = moment('2015-02-25');

function isSameDayAndMonth(m1, m2){
  return m1.date() === m2 .date() && m1.month() === m2.month()
}

console.log( isSameDayAndMonth(m1, m2) );
console.log( isSameDayAndMonth(m1, m3) );
console.log( isSameDayAndMonth(m2, m3) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
like image 177
VincenzoC Avatar answered Oct 12 '22 23:10

VincenzoC