322

I am trying to use momentjs to check if a given date is today or in the future.

This is what I have so far:

<script type="text/javascript" src="http://momentjs.com/downloads/moment.min.js"></script>
<script type="text/javascript">

var SpecialToDate = '31/01/2014'; // DD/MM/YYYY

var SpecialTo = moment(SpecialToDate, "DD/MM/YYYY");
if (moment().diff(SpecialTo) > 0) {
    alert('date is today or in future');
} else {
    alert('date is in the past');
}

</script>

The code is evaluating my date (31st of Jan 2014) as a date in past.

Any idea what I am doing wrong?

0

18 Answers 18

378

You can use the isSame function:

var iscurrentDate = startTime.isSame(new Date(), "day");
if(iscurrentDate) {

}
4
  • 3
    does this match year and month too? Mar 15, 2016 at 20:48
  • 17
    It's must match year and month. moment('2010-01-01').isSame('2011-01-01', 'month'); // false, different year moment('2010-01-01').isSame('2010-02-01', 'day'); // false, different month
    – Wolf
    Mar 16, 2016 at 3:08
  • 8
    This doesn't even answer the OP's question... "today OR IN THE FUTURE", and what is startTime? Date object don't have a isSame method...
    – Sharcoux
    Nov 7, 2018 at 10:58
  • 8
    @Sharcoux This question is about momentjs, so clearly it is a moment object.
    – Nathan
    May 1, 2019 at 19:39
254

After reading the documentation: http://momentjs.com/docs/#/displaying/difference/, you have to consider the diff function like a minus operator.

                   // today < future (31/01/2014)
today.diff(future) // today - future < 0
future.diff(today) // future - today > 0

Therefore, you have to reverse your condition.

If you want to check that all is fine, you can add an extra parameter to the function:

moment().diff(SpecialTo, 'days') // -8 (days)
6
  • 96
    this won't work if it's a different day but the difference is less than 24 hours
    – galki
    May 8, 2016 at 4:59
  • 1
    Working, regardless if time difference is less than 24 hours.
    – zanderwar
    May 12, 2016 at 4:51
  • 6
    Not working for me. If day is +1 in future moment().diff(SpecialTo, 'days') gives me -0 (negative zero)
    – gavroche
    May 31, 2016 at 6:07
  • 2
    Today doesn't mean in next 24 hours. isSame is good solution. Aug 5, 2016 at 13:08
  • 1
    moment().diff(SpecialToDate) will directly give the difference in milliseconds. 'days' is not needed. This will work for all scenarios. SpecialToDate can be '2018-10-26 00:00:00' for an example.
    – backslashN
    Oct 26, 2018 at 16:22
203

Since no one seems to have mentioned it yet, the simplest way to check if a Moment date object is in the past:

momentObj.isBefore()

Or in the future:

momentObj.isAfter()

Just leave the args blank -- that'll default to now.

There's also isSameOrAfter and isSameOrBefore.

N.B. this factors in time. If you only care about the day, see Dipendu's answer.

3
  • 1
    The docs explain that this is undefined behaviour, so you should not do this: momentjs.com/docs/#/query/is-before
    – Dancrumb
    Jan 23, 2018 at 23:43
  • 21
    @Dancrumb Read it again. "If nothing is passed to moment#isBefore, it will default to the current time." The momentObj in my example is an instance of a moment date. The docs are specifically talking about creating a new instance (current time) and then checking if it is in the past, in one statement. I'm not suggesting you do moment().isBefore() which is utterly pointless -- why would you check if now is in the past (or future)?
    – mpen
    Jan 23, 2018 at 23:50
  • 2
    This is the best answer in my opinion, short, precise and effective.
    – Punter Bad
    Jul 24, 2020 at 14:17
186
// Returns true if it is today or false if it's not
moment(SpecialToDate).isSame(moment(), 'day');
0
93

You can use the isAfter() query function of momentjs:

Check if a moment is after another moment.

moment('2010-10-20').isAfter('2010-10-19'); // true

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

moment('2010-10-20').isAfter('2010-01-01', 'year'); // false

moment('2010-10-20').isAfter('2009-12-31', 'year'); // true

http://momentjs.com/docs/#/query/is-after/

2
  • The constructor that takes a date string is deprecated. Aug 11, 2016 at 1:33
  • @VahidAmiri The docs don't mention this. They do however suggest we use string + format constructor if we don't use ISO 8601. So unless one is using some weird date formats it is OK to use just a string.
    – johndodo
    Dec 24, 2018 at 12:12
38

Update

moment().isSame('2010-02-01', 'day'); // Return true if we are the 2010-02-01

I have since found the isSame function, which in I believe is the correct function to use for figuring out if a date is today.

Original answer

Just in case someone else needs this, just do this:

const isToday = moment(0, "HH").diff(date, "days") == 0;

or if you want a function:

isToday = date => moment(0,"HH").diff(date, "days") == 0;

Where date is the date you want to check for.

Explanation

moment(0, "HH") returns today's day at midnight.

date1.diff(date2, "days") returns the number of days between the date1 and date2.

0
32

invert isBefore method of moment to check if a date is same as today or in future like this:

!moment(yourDate).isBefore(moment(), "day");
1
9

To check if it is today:

If we compare two dates which contain also the time information isSame will obviously fail. diff will fail in case that the two dates span over the new day:

var date1 = moment("01.01.2016 23:59:00", "DD.MM.YYYY HH.mm.ss");
var date2 = moment("02.01.2016 00:01:00", "DD.MM.YYYY HH.mm.ss");
var diff = date2.diff(date1); // 2seconds

I think the best way, even if it is not quick and short, is the following:

var isSame = date1.date() == date2.date() && date1.month() == date2.month() && date1.year() == date2.year()

To check if it is in the future:

As suggested also by other users, the diff method works.

var isFuture = now.diff(anotherDate) < 0 
8

If you only need to know which one is bigger, you can also compare them directly:

var SpecialToDate = '31/01/2014'; // DD/MM/YYYY

var SpecialTo = moment(SpecialToDate, "DD/MM/YYYY");
if (moment() > SpecialTo) {
    alert('date is today or in future');
} else {
    alert('date is in the past');
}

Hope this helps!

5

Use the simplest one to check for future date

if(moment().diff(yourDate) >=  0)
     alert ("Past or current date");
else
     alert("It is a future date");
5

I wrote functions that check if a date of Moment type is a Day that Passed or not, as functional and self-descriptive functions. Maybe it is could to help someone.

function isItBeforeToday(MomentDate: Moment) {
  return MomentDate.diff(moment(0, 'HH')) < 0;
}

function isItAfterToday(MomentDate: Moment) {
  return MomentDate.diff(moment(0, 'HH')) > 0;
}

4

if firstDate is same or after(future) secondDate return true else return false. Toda is firstDate = new Date();

  static isFirstDateSameOrAfterSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if(date1 && date2){
      return date1.isSameOrBefore(date2,'day');
    }
    return false;
  }

There is isSame, isBefore and isAfter for day compare moment example;

  static isFirstDateSameSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if (date1 && date2) {
      return date1.isSame(date2,'day');
    }
    return false;
  }

  static isFirstDateAfterSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if(date1 && date2){
      return date1.isAfter(date2,'day');
    }
    return false;
  }

  static isFirstDateBeforeSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if(date1 && date2){
      return date1.isBefore(date2,'day');
    }
    return false;
  }
2

Select yesterday to check past days or not with help of moment().subtract(1, "day");

Reference:- http://momentjs.com/docs/#/manipulating/subtract/

function myFunction() {
  var yesterday = moment().subtract(1, "day").format("YYYY-MM-DD");
  var SpecialToDate = document.getElementById("theDate").value;

  if (moment(SpecialToDate, "YYYY-MM-DD", true).isAfter(yesterday)) {
    alert("date is today or in future");
    console.log("date is today or in future");
  } else {
    alert("date is in the past");
    console.log("date is in the past");
  }
}
<script src="http://momentjs.com/downloads/moment.js"></script>
<input type="date" id="theDate" onchange="myFunction()">

2
function isTodayOrFuture(date){
  date = stripTime(date);
  return date.diff(stripTime(moment.now())) >= 0;
}

function stripTime(date){
  date = moment(date);
  date.hours(0);
  date.minutes(0);
  date.seconds(0);
  date.milliseconds(0);
  return date;
}

And then just use it line this :

isTodayOrFuture(YOUR_TEST_DATE_HERE)
1

If we want difference without the time you can get the date different (only date without time) like below, using moment's format.

As, I was facing issue with the difference while doing ;

moment().diff([YOUR DATE])

So, came up with following;

const dateValidate = moment(moment().format('YYYY-MM-DD')).diff(moment([YOUR SELECTED DATE HERE]).format('YYYY-MM-DD'))

IF dateValidate > 0 
   //it's past day
else
   //it's current or future

Please feel free to comment if there's anything to improve on.

Thanks,

1
  • 3
    Please review How to write a good answer. Code-only answers are discouraged because they do not explain how they resolve the issue. You should update your answer to explain what this does and how it improves on the many answers this question already has. Oct 14, 2017 at 1:30
0

i wanted it for something else but eventually found a trick which you can try

somedate.calendar(compareDate, { sameDay: '[Today]'})=='Today'

var d = moment();
 var today = moment();
 
 console.log("Usign today's date, is Date is Today? ",d.calendar(today, {
    sameDay: '[Today]'})=='Today');
    
 var someRondomDate = moment("2012/07/13","YYYY/MM/DD");
 
 console.log("Usign Some Random Date, is Today ?",someRondomDate.calendar(today, {
    sameDay: '[Today]'})=='Today');
    
  
 var anotherRandomDate =  moment("2012/07/13","YYYY/MM/DD");
 
 console.log("Two Random Date are same date ? ",someRondomDate.calendar(anotherRandomDate, {
    sameDay: '[Today]'})=='Today');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

0

check with following:

let isContinue = moment().diff('2020-04-04T20:06:11+05:30')/1000

it is returning in seconds..

If will check as 2 mins condition then

if (isContinue < 120) {
  ..To check otp details or further logic
} else {
   // otp is getting invalid
}
0

Simplest answer will be:

const firstDate = moment('2020/10/14'); // the date to be checked
const secondDate = moment('2020/10/15'); // the date to be checked

firstDate.startOf('day').diff(secondDate.startOf('day'), 'days'); // result = -1
secondDate.startOf('day').diff(firstDate.startOf('day'), 'days'); // result = 1

It will check with the midnight value and will return an accurate result. It will work also when time diff between two dates is less than 24 hours also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.