The docs are pretty clear that you pass in a second parameter to specify granularity.

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

As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.

For your case you would pass 'day' as the second parameter.

Answer from zzzzBov on Stack Overflow
Top answer
1 of 10
708

I believe you are looking for the query functions, isBefore, isSame, and isAfter.

But it's a bit difficult to tell exactly what you're attempting. Perhaps you are just looking to get the difference between the input time and the current time? If so, consider the difference function, diff. For example:

moment().diff(date_time, 'minutes')

A few other things:

  • There's an error in the first line:

      var date_time = 2013-03-24 + 'T' + 10:15:20:12 + 'Z'
    

    That's not going to work. I think you meant:

      var date_time = '2013-03-24' + 'T' + '10:15:20:12' + 'Z';
    

    Of course, you might as well:

      var date_time = '2013-03-24T10:15:20:12Z';
    
  • You're using: .tz('UTC') incorrectly. .tz belongs to moment-timezone. You don't need to use that unless you're working with other time zones, like America/Los_Angeles.

    If you want to parse a value as UTC, then use:

      moment.utc(theStringToParse)
    

    Or, if you want to parse a local value and convert it to UTC, then use:

      moment(theStringToParse).utc()
    

    Or perhaps you don't need it at all. Just because the input value is in UTC, doesn't mean you have to work in UTC throughout your function.

  • You seem to be getting the "now" instance by moment(new Date()). You can instead just use moment().

Updated

Based on your edit, I think you can just do this:

var date_time = req.body.date + 'T' + req.body.time + 'Z';
var isafter = moment(date_time).isAfter('2014-03-24T01:14:00Z');

Or, if you would like to ensure that your fields are validated to be in the correct format:

var m = moment.utc(req.body.date + ' ' + req.body.time, "YYYY-MM-DD  HH:mm:ss");
var isvalid = m.isValid();
var isafter = m.isAfter('2014-03-24T01:14:00Z');
2 of 10
324

You should be able to compare them directly.

var date = moment("2013-03-24")
var now = moment();

if (now > date) {
   // date is past
} else {
   // date is future
}

$(document).ready(function() {
  
  $('.compare').click(function(e) {
  
    var date = $('#date').val();
  
    var now = moment();
    var then = moment(date);
  
    if (now > then) {
      $('.result').text('Date is past');
    } else {
      $('.result').text('Date is future');
    }

  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>



<input type="text" name="date" id="date" value="2014-12-18"  placeholder="yyyy-mm-dd">
<button class="compare">Compare date to current date</button>
<br>
<div class="result"></div>

Top answer
1 of 16
959

I'm still learning JavaScript, and the only way that I've found which works for me to compare two dates without the time is to use the setHours method of the Date object and set the hours, minutes, seconds and milliseconds to zero. Then compare the two dates.

For example,

date1 = new Date()
date2 = new Date(2011,8,20)

date2 will be set with hours, minutes, seconds and milliseconds to zero, but date1 will have them set to the time that date1 was created. To get rid of the hours, minutes, seconds and milliseconds on date1 do the following:

date1.setHours(0,0,0,0)

Now you can compare the two dates as DATES only without worrying about time elements.

2 of 16
257

BEWARE THE TIMEZONE

Using the date object to represent just-a-date straight away gets you into a huge excess precision problem. You need to manage time and timezone to keep them out, and they can sneak back in at any step. The accepted answer to this question falls into the trap.

A javascript date has no notion of timezone. It's a moment in time (ticks since the epoch) with handy (static) functions for translating to and from strings, using by default the "local" timezone of the device, or, if specified, UTC or another timezone. To represent just-a-date with a date object, you want your dates to represent UTC midnight at the start of the date in question. This is a common and necessary convention that lets you work with dates regardless of the season or timezone of their creation. So you need to be very vigilant to manage the notion of timezone, both when you create your midnight UTC Date object, and when you serialize it.

Lots of folks are confused by the default behaviour of the console. If you spray a date to the console, the output you see will include your timezone. This is just because the console calls toString() on your date, and toString() gives you a local represenation. The underlying date has no timezone! (So long as the time matches the timezone offset, you still have a midnight UTC date object)

Deserializing (or creating midnight UTC Date objects)

This is the rounding step, with the trick that there are two "right" answers. Most of the time, you will want your date to reflect the local timezone of the user. What's the date here where I am.. Users in NZ and US can click at the same time and usually get different dates. In that case, do this...

// create a date (utc midnight) reflecting the value of myDate and the environment's timezone offset.
new Date(Date.UTC(myDate.getFullYear(),myDate.getMonth(), myDate.getDate()));

Sometimes, international comparability trumps local accuracy. In that case, do this...

// the date in London of a moment in time. Device timezone is ignored.
new Date(Date.UTC(myDate.getUTCFullYear(), myDate.getUTCMonth(), myDate.getUTCDate()));

Deserialize a date

Often dates on the wire will be in the format YYYY-MM-DD. To deserialize them, do this...

var midnightUTCDate = new Date( dateString + 'T00:00:00Z');

Serializing

Having taken care to manage timezone when you create, you now need to be sure to keep timezone out when you convert back to a string representation. So you can safely use...

  • toISOString()
  • getUTCxxx()
  • getTime() //returns a number with no time or timezone.
  • .toLocaleDateString("fr",{timeZone:"UTC"}) // whatever locale you want, but ALWAYS UTC.

And totally avoid everything else, especially...

  • getYear(),getMonth(),getDate()

So to answer your question, 7 years too late...

<input type="date" onchange="isInPast(event)">
<script>
var isInPast = function(event){
  var userEntered = new Date(event.target.valueAsNumber); // valueAsNumber has no time or timezone!
  var now = new Date();
  var today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ));
  if(userEntered.getTime() < today.getTime())
    alert("date is past");
  else if(userEntered.getTime() == today.getTime())
    alert("date is today");
  else
    alert("date is future");

}
</script>

See it running...

Update 2022... free stuff with tests ...

The code below is now an npm package, Epoq. The code is on github. You're welcome :-)

Update 2019... free stuff...

Given the popularity of this answer, I've put it all in code. The following function returns a wrapped date object, and only exposes those functions that are safe to use with just-a-date.

Call it with a Date object and it will resolve to JustADate reflecting the timezone of the user. Call it with a string: if the string is an ISO 8601 with timezone specified, we'll just round off the time part. If timezone is not specified, we'll convert it to a date reflecting the local timezone, just as for date objects.

function JustADate(initDate){
  var utcMidnightDateObj = null
  // if no date supplied, use Now.
  if(!initDate)
    initDate = new Date();

  // if initDate specifies a timezone offset, or is already UTC, just keep the date part, reflecting the date _in that timezone_
  if(typeof initDate === "string" && initDate.match(/(-\d\d|(\+|-)\d{2}:\d{2}|Z)$/gm)){  
     utcMidnightDateObj = new Date( initDate.substring(0,10) + 'T00:00:00Z');
  } else {
    // if init date is not already a date object, feed it to the date constructor.
    if(!(initDate instanceof Date))
      initDate = new Date(initDate);
      // Vital Step! Strip time part. Create UTC midnight dateObj according to local timezone.
      utcMidnightDateObj = new Date(Date.UTC(initDate.getFullYear(),initDate.getMonth(), initDate.getDate()));
  }

  return {
    toISOString:()=>utcMidnightDateObj.toISOString(),
    getUTCDate:()=>utcMidnightDateObj.getUTCDate(),
    getUTCDay:()=>utcMidnightDateObj.getUTCDay(),
    getUTCFullYear:()=>utcMidnightDateObj.getUTCFullYear(),
    getUTCMonth:()=>utcMidnightDateObj.getUTCMonth(),
    setUTCDate:(arg)=>utcMidnightDateObj.setUTCDate(arg),
    setUTCFullYear:(arg)=>utcMidnightDateObj.setUTCFullYear(arg),
    setUTCMonth:(arg)=>utcMidnightDateObj.setUTCMonth(arg),
    addDays:(days)=>{
      utcMidnightDateObj.setUTCDate(utcMidnightDateObj.getUTCDate + days)
    },
    toString:()=>utcMidnightDateObj.toString(),
    toLocaleDateString:(locale,options)=>{
      options = options || {};
      options.timeZone = "UTC";
      locale = locale || "en-EN";
      return utcMidnightDateObj.toLocaleDateString(locale,options)
    }
  }
}


// if initDate already has a timezone, we'll just use the date part directly
console.log(JustADate('1963-11-22T12:30:00-06:00').toLocaleDateString())
// Test case from @prototype's comment
console.log("@prototype's issue fixed... " + JustADate('1963-11-22').toLocaleDateString())

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-compare-only-date-in-momentjs
How To Compare Only Date In Moment.js? - GeeksforGeeks
July 23, 2025 - In this approach, we are using the format method to convert both date1 and date2 to strings in the 'YYYY-MM-DD' format, which represents only the date part of each moment object. By comparing these formatted date strings, we determine if the ...
🌐
GitHub
github.com › moment › moment › issues › 3455
How to represent dates (without time) and times (without date)? · Issue #3455 · moment/moment
September 19, 2016 - A Moment.js object (like its underlying Date object) always represents an exact point in time. Sometimes, however, I just want to store a date (say 2016-09-19). This is not a point in time, but a c...
Author   DanielSWolf
🌐
Educative
educative.io › answers › how-to-compare-dates-with-date-object-and-momentjs-in-javascript
How to compare dates with Date object and Moment.js in JavaScript
JavaScript provides built-in Date object to handle everyday use of date and time. It also supports a lot of libraries like Moment.js, Luxon, and Day.js, that provide more functionalities than the built-in Date object. The Date object is created using the new operator, and we can even initialize by passing the data to the constructor of the Date. Below is the syntax to create a new object of the Date type: ... The Date object allows the use of comparison operators like <, <=, >, >=, or =, and we can compare two dates using these operators.
Find elsewhere
🌐
IQCode
iqcode.com › code › javascript › compare-two-dates-using-moment
compare two dates using moment Code Example
November 20, 2021 - moment('2010-10-20').isAfter('2010-01-01', 'year'); // false moment('2010-10-20').isAfter('2009-12-31', 'year'); // true
🌐
DEV Community
dev.to › onlinemsr › javascript-compare-dates-from-chaos-to-clarity-1g23
JavaScript Compare Dates: From Chaos to Clarity - DEV Community
May 6, 2024 - You have learned how to compare dates without time, with time, by day, in different time zones, using natural language, relative time, or custom formats. You have also learned how to use some of the most popular and useful libraries for working with dates in JavaScript, such as Moment.js, Day.js, and date-fns.
🌐
Medium
sixth-density-jg.medium.com › how-to-compare-dates-with-moment-js-a69be9a0effa
How to Compare Dates with Moment.js | by Jay Gao | Medium
February 24, 2023 - // Create two Moment.js objects representing dates const date1 = moment('2022-05-30'); const date2 = moment('2022-06-01'); // Compare the two dates const diffInDays = date2.diff(date1, 'days'); // returns 2 if (diffInDays > 0) { console.log('date2 is after date1'); } else if (diffInDays < 0) { console.log('date2 is before date1'); } else { console.log('date1 and date2 are the same'); }
🌐
GitHub
github.com › moment › moment › issues › 1199
How to compare only HH:mm? · Issue #1199 · moment/moment
October 20, 2013 - isWithinTime: function(end) { var moment = require('moment'); var now = moment(new Date()).format('HH:mm'); var end = moment(new Date(end)).format('HH:mm'); if (now.toString() > end.toString()) { return false; } return true; } I want to compare only time in HH:mm format.
Author   artworkad
🌐
Moment.js
momentjs.com › docs
Moment.js | Docs
Display Format Time from now Time from X Time to now Time to X Calendar Time Difference Unix Timestamp (milliseconds) Unix Timestamp (seconds) Days in Month As Javascript Date As Array As JSON As ISO 8601 String As Object As String Inspect · Query Is Before Is Same Is After Is Same or Before Is Same or After Is Between Is Daylight Saving Time Is DST Shifted Is Leap Year Is a Moment Is a Date
🌐
GitHub
github.com › moment › moment › issues › 1269
No way to (easily) compare the date part of 2 moments · Issue #1269 · moment/moment
November 14, 2013 - I have been digging through docs and racking my brain, but it seems that taking two moment objects and comparing just the date (whole date) to see if they represent the same exact day is not supported directly. There should be a simple way to do this. ... You can’t perform that action at this time.
Author   tommck
🌐
GitHub
github.com › moment › moment › issues › 3568
Only want to compare TIME values MomentJS · Issue #3568 · moment/moment
November 5, 2016 - Any other suggestions for accomplishing this and simply ignoring the day/date? I'm finding it hard to believe that it's this complex, but maybe it is :\ ... Here's further clarification that issue arises with spanning days, even when trying to be more explicit: var currentTime= moment('11:00p', "HH:mm a"); var startTime = moment('06:00p', "HH:mm a"); var endTime = moment('03:30a', "HH:mm a"); currentTime.toString(); //"Fri Oct 28 2016 23:00:00 GMT-0400" startTime.toString(); // "Fri Oct 28 2016 18:00:00 GMT-0400" endTime.toString(); // "Fri Oct 28 2016 03:30:00 GMT-0400" currentTime.isBetween(startTime, endTime); // false currentTime.isAfter(endTime) && currentTime.isBefore(startTime); //false currentTime.isAfter(startTime) && currentTime.isBefore(endTime); //false
Author   rfossella
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-to-compare-only-dates-in-moment-js-e2421ced3318
How to Compare Only Dates in Moment.js | by John Au-Yeung | JavaScript in Plain English
July 19, 2024 - There’s also the isSameOrAfter method that takes the same arguments and lets us compare if one date is the same or after a given unit. ... const isSameOrAfter = moment('2010-10-20').isSameOrAfter('2010-01-01', 'year'); console.log(isSameOrAfter)
🌐
TutorialsPoint
tutorialspoint.com › How-to-compare-two-dates-with-JavaScript
How to compare two dates with JavaScript?
August 17, 2022 - </h4> <p id = "output"> </p> <script> let output = document.getElementById("output"); function compareDates( date1, date2 ) { if ( date1.getTime() < date2.getTime() ) { output.innerHTML += date1 + " is behind the " + date2 + " <br/> "; } else if ( date1 > date2 ) { output.innerHTML += date2 + " is behind the " + date1 + " <br/> "; } else { output.innerHTML += date1 + " is same as " + date2 + " <br/> "; } } // calling the function for different expressions output.innerHTML += "<br/>"; let date1 = new Date(); let date2 = new Date(2012, 11, 21); compareDates( date1, date2 ); output.innerHTML += "<br/>"; date2 = new Date(); compareDates( date1, date2 ); </script> </body> </html> JavaScript contains various libraries; one of them is Moment.js which is used to manage the date and time.
🌐
Readthedocs
momentjscom.readthedocs.io › en › latest › moment › 05-query › 02-is-same
Is Same - momentjs.com
moment('2010-10-20').isSame('2009-12-31', 'year'); // false moment('2010-10-20').isSame('2010-01-01', 'year'); // true moment('2010-10-20').isSame('2010-12-31', 'year'); // true moment('2010-10-20').isSame('2011-01-01', 'year'); // false
🌐
freeCodeCamp
freecodecamp.org › news › javascript-date-comparison-how-to-compare-dates-in-js
JavaScript Date Comparison – How to Compare Dates in JS
November 7, 2024 - In this article, you have learned how to do date comparisons in JavaScript using the date Object without having to install any library.