Comparing Date Part Only Without Comparing Time in JavaScript

Comparing date part only without comparing time in JavaScript

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.

How to compare the date part alone from a date time value

Try clearing the time using Date.setHours:

dateObj.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])

Example Code:

var today = new Date();
today.setHours(0, 0, 0, 0);
d = new Date(my_value);
d.setHours(0, 0, 0, 0);

if(d >= today){
alert(d is greater than or equal to current date);
}

Javascript - Comparing dates without time

The simplest way to get the number of whole days between two dates is to create two date objects for the subject dates that are set to the same time. Noon is convenient as it means the date part is unaffected by daylight saving (some places introduce it at midnight) if you happen to print out just the date part.

The following does all calculations in the time zone of the host system. UTC could be used (and the hours set to 0 as daylight saving isn't an issue at all), but it's more to type.

E.g.:

function differenceInDays(d0, d1) {  // Copy dates so don't affect originals  d0 = new Date(+d0);  d1 = new Date(+d1);
// Set to noon d0.setHours(12,0,0,0); d1.setHours(12,0,0,0);
// Get difference in whole days, divide by milliseconds in one day // and round to remove any daylight saving boundary effects return Math.round((d1-d0) / 8.64e7)}
// Difference between 2015-11-12T17:35:32.124 and 2015-12-01T07:15:54.999document.write(differenceInDays(new Date(2015,10,12,17,35,32,124), new Date(2015,11,01,07,15,54,999)));

Javascript date comparison ignoring timestamp value

You could use toDateString to get rid of the the time, and reassign that to the firstDate and secondDate variables. There might be a better way, but this is what came to mind for me.

firstDate = new Date(firstDate.toDateString());
secondDate = new Date(secondDate.toDateString());
if(firstDate < secondDate){
alert("This alert shouldn't pop out as dates are equal");
}

Also, you'll want to make sure you're comparing the values of the dates, and not checking if they're the same object when you compare if they're equal. So something like.

firstDate.valueOf() == secondDate.valueOf()

You can also check out my JSFiddle example.

How to compare two dates without hours in javascript?

What you are doing here is comparing two different instances (two different references) of Date object, which lead to an unexpected result

You could try to compare the millisecond of these by using getTime

const date = "28.02.2022";
const meeting = { date: "2022-02-28 14:30:00" }

const firstDate = new Date(`${date.split(".").reverse().join("-")}`);
const secondDate = new Date(`${meeting.date.split(" ")[0]}`)

firstDate.setHours(0,0,0,0);
secondDate.setHours(0,0,0,0);

console.log(firstDate, secondDate, firstDate.getTime() === secondDate.getTime());

How to compare only date in moment.js

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.

Compare two dates with JavaScript

The Date object will do what you want - construct one for each date, then compare them using the >, <, <= or >=.

The ==, !=, ===, and !== operators require you to use date.getTime() as in

var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();

to be clear just checking for equality directly with the date objects won't work

var d1 = new Date();
var d2 = new Date(d1);

console.log(d1 == d2); // prints false (wrong!)
console.log(d1 === d2); // prints false (wrong!)
console.log(d1 != d2); // prints true (wrong!)
console.log(d1 !== d2); // prints true (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)

I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.


For the curious, date.getTime() documentation:

Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)



Related Topics



Leave a reply



Submit