Comparing date part only without comparing time in JavaScript
Asked Answered
W

28

538

What is wrong with the code below?

Maybe it would be simpler to just compare date and not time. I am not sure how to do this either, and I searched, but I couldn't find my exact problem.

BTW, when I display the two dates in an alert, they show as exactly the same.

My code:

window.addEvent('domready', function() {
    var now = new Date();
    var input = $('datum').getValue();
    var dateArray = input.split('/');
    var userMonth = parseInt(dateArray[1])-1;
    var userDate = new Date();
    userDate.setFullYear(dateArray[2], userMonth, dateArray[0], now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());

    if (userDate > now)
    {
        alert(now + '\n' + userDate);
    }
});

Is there a simpler way to compare dates and not including the time?

Westerfield answered 23/4, 2010 at 13:8 Comment(2)
date1.toDateString() === date2.toDateString()Donettedoney
Raised from the dead: I am getting broken results from date.setFullYear(yyyy,mm,dd) when using toSting on the date I get the month has increased by 1. Tested on this page link in both FireFox & Edge.Pelaga
P
952

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.

Performative answered 1/6, 2011 at 13:46 Comment(10)
Please be aware that testing by date1 === date2 does not seem to provide consistent behaviour; it's better to do date1.valueOf() === b.valueOf() or even date1.getTime() === date2.getTime(). Strangeness.Opia
Be careful : if date1 and date2 are in winter and summer, and you plan to iterate from one to the other with addDays(1), the problem is that they won't have the same timezone because of the daylight saving, so the last compare that should give equal dates will not work because the two date are not really at 00:00:00:0.Zehe
I know this is an old question, but it comes up first in google when searching. Be careful with this answer. This will give incorrect answers if the user is not in the same time zone as the creator of the date object. For example, change the timezone on your computer's OS to East Coast (US) time. Open the console of your browser and type var date2 = new Date(2011,8,20). Now change the OS's time zone to Pacific Time (US). In the same browser console type date2.toDateString() and you'll get back Mon Sep 19 2011 rather than Tuesday the 20th!Waterloo
Also note that setHours() sets time based on current timezone, that automatically detected by browser. Try: t = new Date("2016-02-29T01:45:49.098Z"); t.setHours(0,0,0,0); console.log(t.toJSON()); will print "2016-02-28T15:00:00.000Z", date 28, but not 29 My current time zone is Asia/TokyoOunce
My recommendation concerning the timezone/daylight savings misery is this: When getting user input, use the local time methods to input the date. When outputting/formatting the date, use the local time methods as well. For all other stuff, use the UTC methods to make sure you are comparing apples to apples.Suffuse
This answer really should be updated to use setUTCxxx methods instead of the local/timezone aware variants.Suffuse
Yup. This answer falls into the trap. I discuss timezone in my answer. Sometimes you want local timezone when you create the date (Click if today is your birthday), but you never want a time part in the stored value. The stored value (the Date object) should always point to UTC midnight of the day in question.Sensorium
@ErwinWessels Use getTime() to compare Date objects. They're not meant to be directly comparable.Sensorium
hope this may also prove helpful :) toDateString() w3schools.com/jsref/jsref_todatestring.aspBanta
this worked for me. i am using datepicker and i am comparing today's date and previously selected date. thanks for sharing the answer.Tartarous
S
254

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())
Sensorium answered 27/6, 2016 at 9:52 Comment(5)
Your answer contains really valuable info! Unfortunately you did not actually add the answer to OP's actual question, preventing me from upvoting it. Try adding in a small code snippet that answers OP's question.Suffuse
Ha ha ha @ '7 years too late'! I like your style user1585345! You got my vote!Suffuse
I found this to be helpful. Note there is a typo in the " international comparability" snippet. I think it should be: new Date(Date.UTC(myDate.getUTCFullYear(), myDate.getUTCMonth(), myDate.getUTCDate()));Felonious
Note that this wraps a date+time the time set to just past the stroke of midnight UTC, and that date+time can be interpreted differently by locale. For instance, JustADate('1963-11-22').toLocaleDateString() returns "11/21/1963" which is the prior date in time zones west of the Atlantic. So if the goal is to interpret a date string to display the same calendar date in another format, instead of wrapping a Date set to UTC, it might be better to modify wrap an sstMidnightDateObj set to SST (American Samoa Time) instead, so returns the same calendar date in (almost) all locales.Appomattox
@Appomattox your issue was due to the fact that new Date("yyyy-MM-dd") does actually create a midnight UTC date object, (At least in Chrome. It may be implementation dependant). This was not well managed in my code, but it's fixed now.Sensorium
L
103

How about this?

Date.prototype.withoutTime = function () {
    var d = new Date(this);
    d.setHours(0, 0, 0, 0);
    return d;
}

It allows you to compare the date part of the date like this without affecting the value of your variable:

var date1 = new Date(2014,1,1);
new Date().withoutTime() > date1.withoutTime(); // true
Loquacity answered 13/4, 2015 at 9:45 Comment(4)
This is by far the most elegant answer to the original post. I did not create a separate function for my purposes, just included the two lines of code.Edelweiss
Add custom functionality to the prototype is not so good idea.Momentous
Why @andrey.shedko? Saying something is a bad idea or is the wrong way without your reasoning is bad for everyone. If it works and is something you re-use throughout your project and can save you repeated manual pruning it works justt fine and is fine to use.Uncritical
As noted in the accepted answer that uses setHours, this will give the wrong time if you have a timezone other than UTC/GMT. The withoutTime prototype could be updated to use the Date.UTC method.Koball
R
29

Using Moment.js

If you have the option of including a third-party library, it's definitely worth taking a look at Moment.js. It makes working with Date and DateTime much, much easier.

For example, seeing if one Date comes after another Date but excluding their times, you would do something like this:

var date1 = new Date(2016,9,20,12,0,0); // October 20, 2016 12:00:00
var date2 = new Date(2016,9,20,12,1,0); // October 20, 2016 12:01:00

// Comparison including time.
moment(date2).isAfter(date1); // => true

// Comparison excluding time.
moment(date2).isAfter(date1, 'day'); // => false

The second parameter you pass into isAfter is the precision to do the comparison and can be any of year, month, week, day, hour, minute or second.

Roper answered 10/7, 2016 at 19:50 Comment(4)
got a 100x speedup moving from a momentjs solution to a Date() + sethours solution. careful friends :-)Biagio
@Biagio Interesting. Definitely good to know the performance impact. How many operations did you use for your benchmark?Roper
i was at around 1mil comparisons. didnt setup an actual benchmarkBiagio
Moment is in maintenance mode and should no longer be used if you're not using it already. There are alternatives, and the date object is better than it used to be.Sensorium
S
26

Simply compare using .toDateString like below:

new Date().toDateString();

This will return you date part only and not time or timezone, like this:

"Fri Feb 03 2017"

Hence both date can be compared in this format likewise without time part of it.

Saddletree answered 3/2, 2017 at 9:8 Comment(3)
That's a good start, but it won't allow for comparisons because it's now a string. To compare, change it back to a Date object by doing new Date(new Date().toDateString());Manganite
@GridTrekkor True, but if you just want a quick equality test this is the most simple solution.Saguache
As much as possible I do not want to use another lib. This is perfect!Chantell
H
18

If you are truly comparing date only with no time component, another solution that may feel wrong but works and avoids all Date() time and timezone headaches is to compare the ISO string date directly using string comparison:

> "2019-04-22" <= "2019-04-23"
true
> "2019-04-22" <= "2019-04-22"
true
> "2019-04-22" <= "2019-04-21"
false
> "2019-04-22" === "2019-04-22"
true

You can get the current date (UTC date, not neccesarily the user's local date) using:

> new Date().toISOString().split("T")[0]
"2019-04-22"

My argument in favor of it is programmer simplicity -- you're much less likely to botch this than trying to handle datetimes and offsets correctly, probably at the cost of speed (I haven't compared performance)

Haplology answered 21/4, 2019 at 11:55 Comment(2)
You can also do new Date().toISOString().substr(0, 10) // "2019-04-22".Diffusive
For the local date (non-UTC date) you can use new Date().toLocaleDateString() // "8/26/2019". But then comparing the text won't be accurate (like "8/26/2019" >= "9/29/2001" is false). So you'll need to convert it new Date(new Date().toLocaleDateString()) to accurately compare to another Date.Diffusive
L
17

Just use toDateString() on both dates. toDateString doesn't include the time, so for 2 times on the same date, the values will be equal, as demonstrated below.

var d1 = new Date(2019,01,01,1,20)
var d2 = new Date(2019,01,01,2,20)
console.log(d1==d2) // false
console.log(d1.toDateString() == d2.toDateString()) // true

Obviously some of the timezone concerns expressed elsewhere on this question are valid, but in many scenarios, those are not relevant.

Logographic answered 16/5, 2019 at 19:56 Comment(1)
In my case this solution is much better than the selected answer and the more-voted answers. It's explicitly said in the title "without comparing time", this solution does exactly so, saving the need for setting the time to manipulate the comparison. To answer "Did event X and event Y happen on the same day" it makes more sense to compare just date, rather than to answer "Is 00:00:00.00 AM of the date of event X exactly the same with 00:00:00.00 of the date of event Y?" which is what many other answerers are doingCammiecammy
R
10

This might be a little cleaner version, also note that you should always use a radix when using parseInt.

window.addEvent('domready', function() {
    // Create a Date object set to midnight on today's date
    var today = new Date((new Date()).setHours(0, 0, 0, 0)),
    input = $('datum').getValue(),
    dateArray = input.split('/'),
    // Always specify a radix with parseInt(), setting the radix to 10 ensures that
    // the number is interpreted as a decimal.  It is particularly important with
    // dates, if the user had entered '09' for the month and you don't use a
    // radix '09' is interpreted as an octal number and parseInt would return 0, not 9!
    userMonth = parseInt(dateArray[1], 10) - 1,
    // Create a Date object set to midnight on the day the user specified
    userDate = new Date(dateArray[2], userMonth, dateArray[0], 0, 0, 0, 0);

    // Convert date objects to milliseconds and compare
    if(userDate.getTime() > today.getTime())
    {
            alert(today+'\n'+userDate);
    }
});

Checkout the MDC parseInt page for more information about the radix.

JSLint is a great tool for catching things like a missing radix and many other things that can cause obscure and hard to debug errors. It forces you to use better coding standards so you avoid future headaches. I use it on every JavaScript project I code.

Retro answered 1/6, 2011 at 22:47 Comment(2)
@EmKay This shouldn't be as big of an issue now as ES5 is fairly standard in most browsers and it forbids the octal interpretation BUT some browsers might still be using the old octal interpretation for backwards compatibility reasons, so I would keep using a radix for the foreseeable future.Retro
If you use strict mode octal interpretations will throw errors, which is a good thing because it helps you find errors that might be misinterpreted.Retro
R
8

An efficient and correct way to compare dates is:

Math.floor(date1.getTime() / 86400000) > Math.floor(date2.getTime() / 86400000);

It ignores the time part, it works for different timezones, and you can compare for equality == too. 86400000 is the number of milliseconds in a day (= 24*60*60*1000).

Beware that the equality operator == should never be used for comparing Date objects because it fails when you would expect an equality test to work because it is comparing two Date objects (and does not compare the two dates) e.g.:

> date1;
outputs: Thu Mar 08 2018 00:00:00 GMT+1300

> date2;
outputs: Thu Mar 08 2018 00:00:00 GMT+1300

> date1 == date2;
outputs: false

> Math.floor(date1.getTime() / 86400000) == Math.floor(date2.getTime() / 86400000);
outputs: true

Notes: If you are comparing Date objects that have the time part set to zero, then you could use date1.getTime() == date2.getTime() but it is hardly worth the optimisation. You can use <, >, <=, or >= when comparing Date objects directly because these operators first convert the Date object by calling .valueOf() before the operator does the comparison.

Rentsch answered 8/3, 2018 at 1:35 Comment(6)
won't work; example new Date (2017, 10, 2, 1).getTime()/86400000 change hour to 2 and you get a different integer (floor) result.Danube
@omu Perhaps you need to learn to test better. It does work, although rather ugly. Perhaps needs rounding to nearest second if times are to nanosecond, but other answers have same fault. I think some of the other answers are better for clarity and maintainance.Rentsch
Math.round won't help, try it in chrome dev tools console, new Date (2017, 10, 2, 1).getTime()/86400000, using Math.round you'll get different results at hour 12 and 13Danube
@omu You are starting the bleeding obvious and I didn't say Math.round() would work: how you code it depends upon your epsilon. And saying Math.floor() doesn't work at 12 and 13 is saying that Math.floor() does work!!! So far you haven't actually included the Math.floor() code you believe doesn't work. I tested using Math.floor(), and had no problem. Please include a fully worked example using Math.floor() and give the outputs you get.Rentsch
@omu Link to a jsbin.com (or equivalent) that demonstrates your problem. I don't work in JavaScript any more, and I am not really that keen to help you solve your problem :-)Rentsch
my problem is solved, I'm just saying the solution you've posted is wrongDanube
C
4

As I don't see here similar approach, and I'm not enjoying setting h/m/s/ms to 0, as it can cause problems with accurate transition to local time zone with changed date object (I presume so), let me introduce here this, written few moments ago, lil function:

+: Easy to use, makes a basic comparison operations done (comparing day, month and year without time.)
-: It seems that this is a complete opposite of "out of the box" thinking.

function datecompare(date1, sign, date2) {
    var day1 = date1.getDate();
    var mon1 = date1.getMonth();
    var year1 = date1.getFullYear();
    var day2 = date2.getDate();
    var mon2 = date2.getMonth();
    var year2 = date2.getFullYear();
    if (sign === '===') {
        if (day1 === day2 && mon1 === mon2 && year1 === year2) return true;
        else return false;
    }
    else if (sign === '>') {
        if (year1 > year2) return true;
        else if (year1 === year2 && mon1 > mon2) return true;
        else if (year1 === year2 && mon1 === mon2 && day1 > day2) return true;
        else return false;
    }    
}

Usage:

datecompare(date1, '===', date2) for equality check,
datecompare(date1, '>', date2) for greater check,
!datecompare(date1, '>', date2) for less or equal check

Also, obviously, you can switch date1 and date2 in places to achieve any other simple comparison.

Caitlin answered 25/3, 2015 at 22:45 Comment(1)
Nice one, plus plus, helped me out, now hopefully the iso conversions don't bite, haha, thx.Beehive
B
3

This JS will change the content after the set date here's the same thing but on w3schools

date1 = new Date()
date2 = new Date(2019,5,2) //the date you are comparing

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

var stockcnt = document.getElementById('demo').innerHTML;
if (date1 > date2){
document.getElementById('demo').innerHTML="yes"; //change if date is > set date (date2)
}else{
document.getElementById('demo').innerHTML="hello"; //change if date is < set date (date2)
}
<p id="demo">hello</p> <!--What will be changed-->
<!--if you check back in tomorrow, it will say yes instead of hello... or you could change the date... or change > to <-->
Biegel answered 1/5, 2019 at 12:46 Comment(0)
M
2

The date.js library is handy for these things. It makes all JS date-related scriping a lot easier.

Motorboat answered 23/4, 2010 at 13:21 Comment(1)
Can you add more information on how this library makes this easier?Lookeron
D
2

This is the way I do it:

var myDate  = new Date($('input[name=frequency_start]').val()).setHours(0,0,0,0);
var today   = new Date().setHours(0,0,0,0);
if(today>myDate){
    jAlert('Please Enter a date in the future','Date Start Error', function(){
        $('input[name=frequency_start]').focus().select();
    });
}
Deutzia answered 6/11, 2011 at 20:10 Comment(2)
I currently use this in production and I do not have any issue or browser incompatibility etc... any reasons why you are saying that getTime() is required ?Deutzia
Please be aware that setHours() modifies the object it is called on, and returns the date as a number of milliseconds (equivalent to calling getTime()). Therefore your today variable is not a Date object like some would expect, but is actually an integer number of milliseconds. As a side-effect this is why you didn't need to call getTime() before comparing, since you already have in an obscure manner.Cyma
P
2

After reading this question quite same time after it is posted I have decided to post another solution, as I didn't find it that quite satisfactory, at least to my needs:

I have used something like this:

var currentDate= new Date().setHours(0,0,0,0);

var startDay = new Date(currentDate - 86400000 * 2);
var finalDay = new Date(currentDate + 86400000 * 2);

In that way I could have used the dates in the format I wanted for processing afterwards. But this was only for my need, but I have decided to post it anyway, maybe it will help someone

Presswork answered 21/1, 2014 at 9:19 Comment(1)
Please note your currentDate variable isn't a date, it's a number of milliseconds since 1970-01-01. The setHours() method modifies the date object it is called on, and returns the equivalent of getTime() (value of date in milliseconds since 1970-01-01).Cyma
R
2

This works for me:

 export default (chosenDate) => {
  const now = new Date();
  const today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
  const splitChosenDate = chosenDate.split('/');

  today.setHours(0, 0, 0, 0);
  const fromDate = today.getTime();
  const toDate = new Date(splitChosenDate[2], splitChosenDate[1] - 1, splitChosenDate[0]).getTime();

  return toDate < fromDate;
};

In accepted answer, there is timezone issue and in the other time is not 00:00:00

Renferd answered 9/12, 2019 at 11:10 Comment(0)
C
2

Using javascript you can set time values to zero for existing date objects and then parse back to Date. After parsing back to Date, Time value is 0 for both and you can do further comparison .

      let firstDate = new Date(mydate1).setHours(0, 0, 0, 0);
      let secondDate = new Date(mydate2).setHours(0, 0, 0, 0);

      if (firstDate == secondDate)
      {
        console.log('both dates are on same day');
      }
      else
      {
        console.log(`both dates are not on same day`);
      }
Choric answered 4/12, 2022 at 19:45 Comment(0)
D
1

Make sure you construct userDate with a 4 digit year as setFullYear(10, ...) !== setFullYear(2010, ...).

Durant answered 23/4, 2010 at 13:31 Comment(0)
S
1

You can use some arithmetic with the total of ms.

var date = new Date(date1);
date.setHours(0, 0, 0, 0);

var diff = date2.getTime() - date.getTime();
return diff >= 0 && diff < 86400000;

I like this because no updates to the original dates are made and perfom faster than string split and compare.

Hope this help!

Sulfuric answered 27/1, 2016 at 12:11 Comment(0)
L
1

Comparing with setHours() will be a solution. Sample:

var d1 = new Date();
var d2 = new Date("2019-2-23");
if(d1.setHours(0,0,0,0) == d2.setHours(0,0,0,0)){
    console.log(true)
}else{
    console.log(false)
}
Lithe answered 23/2, 2019 at 15:1 Comment(0)
S
1
var fromdate = new Date(MM/DD/YYYY);
var todate = new Date(MM/DD/YYYY);
if (fromdate > todate){
    console.log('False');
}else{
    console.log('True');
}

if your date formate is different then use moment.js library to convert the format of your date and then use above code for compare two date

Example :

If your Date is in "DD/MM/YYYY" and wants to convert it into "MM/DD/YYYY" then see the below code example

var newfromdate = new Date(moment(fromdate, "DD/MM/YYYY").format("MM/DD/YYYY"));
console.log(newfromdate);
var newtodate = new Date(moment(todate, "DD/MM/YYYY").format("MM/DD/YYYY"));
console.log(newtodate);

Splenic answered 26/2, 2019 at 9:28 Comment(0)
C
1

Use a library that knows what it's doing

https://day.js.org/docs/en/query/is-same-or-before

dayjs().isSameOrBefore(date, 'day')
Craigcraighead answered 10/2, 2023 at 17:28 Comment(0)
C
0

I know this question have been already answered and this may not be the best way, but in my scenario its working perfectly, so I thought it may help someone like me.

if you have date string as

String dateString="2018-01-01T18:19:12.543";

and you just want to compare the date part with another Date object in JS,

var anotherDate=new Date(); //some date

then you have to convert the string to Date object by using new Date("2018-01-01T18:19:12.543");

and here is the trick :-

var valueDate =new Date(new Date(dateString).toDateString());

            return valueDate.valueOf() == anotherDate.valueOf(); //here is the final result

I have used toDateString() of Date object of JS, which returns the Date string only.

Note: Don't forget to use the .valueOf() function while comparing the dates.

more info about .valeOf() is here reference

Happy codding.

Chester answered 5/1, 2018 at 10:24 Comment(0)
Q
0

This will help. I managed to get it like this.

var currentDate = new Date(new Date().getFullYear(), new Date().getMonth() , new Date().getDate())
Quickwitted answered 28/6, 2018 at 14:34 Comment(0)
D
0

You can use fp_incr(0). Which sets the timezone part to midnight and returns a date object.

Drinkwater answered 18/7, 2019 at 17:9 Comment(0)
B
0

Compare Date and Time:

var t1 = new Date(); // say, in ISO String =  '2022-01-21T12:30:15.422Z'
var t2 = new Date(); // say, in ISO String =  '2022-01-21T12:30:15.328Z'
var t3 = t1;

Compare 2 date objects by milliseconds level:

console.log(t1 === t2); // false - Bcos there is some milliseconds difference
console.log(t1 === t3); // true - Both dates have milliseconds level same values

Compare 2 date objects ONLY by date (Ignore any time difference):

console.log(t1.toISOString().split('T')[0] === t2.toISOString().split('T')[0]); 
                                        // true; '2022-01-21' === '2022-01-21'

Compare 2 date objects ONLY by time(ms) (Ignore any date difference):

console.log(t1.toISOString().split('T')[1] === t3.toISOString().split('T')[1]); 
                                      // true; '12:30:15.422Z' === '12:30:15.422Z'

Above 2 methods uses toISOString() method so you no need to worry about the time zone difference across the countries.

Blondell answered 21/1, 2022 at 12:52 Comment(0)
F
0

One option that I ended up using was to use the diff function of Moment.js. By calling something like start.diff(end, 'days') you can compare difference in whole numbers of days.

Festination answered 17/5, 2022 at 15:8 Comment(0)
G
0

Works for me: I needed to compare a date to a local dateRange

let dateToCompare = new Date().toLocaleDateString().split("T")[0])
let compareTime = new Date(dateToCompare).getTime()

let startDate = new Date().toLocaleDateString().split("T")[0])
let startTime = new Date(startDate).getTime()

let endDate = new Date().toLocaleDateString().split("T")[0])
let endTime = new Date(endDate).getTime()

return compareTime >= startTime && compareTime <= endTime
Giraffe answered 25/7, 2022 at 6:21 Comment(0)
T
0

As per usual. Too little, too late.

Nowadays use of momentjs is discouraged (their words, not mine) and dayjs is preferred.

One can use dayjs's isSame.

https://day.js.org/docs/en/query/is-same

dayjs().isSame('2011-01-01', 'date')

There are also a bunch of other units you can use for the comparisons: https://day.js.org/docs/en/manipulate/start-of#list-of-all-available-units

Transubstantiate answered 10/10, 2022 at 10:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.