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.)
how to compare two string dates in javascript?
var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
alert ("Error!");
}
Demo Jsfiddle
Recently found out from a comment you can directly compare strings like below
if ("2012-11-01" < "2012-11-04") {
alert ("Error!");
}
How to compare two dates from input?
This is how I would do it
HTML
<script>
function compareDates() {
//Get the text in the elements
var from = document.getElementById('from').textContent;
var to = document.getElementById('to').textContent;
//Generate an array where the first element is the year, second is month and third is day
var splitFrom = from.split('/');
var splitTo = to.split('/');
//Create a date object from the arrays
var fromDate = Date.parse(splitFrom[0], splitFrom[1] - 1, splitFrom[2]);
var toDate = Date.parse(splitTo[0], splitTo[1] - 1, splitTo[2]);
//Return the result of the comparison
return fromDate < toDate;
}
</script>
<input id="from" type="date" placeholder="dd/mm/yy"><br>
<input id="to" type="date" placeholder="dd/mm/yy">
<button onclick="compareDates()">Compare</button>
Let me know how you get on.
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.
Compare two dates in Javascript from an HTML form
Try it:
// You were wrong comparing only the year with the full datevar todaysYear = new Date().getFullYear();
var borndate = document.getElementById("borndate");var form = document.querySelector("form");// Working with forms we want to catch submit (not click) eventsform.addEventListener('submit', comparedate)
function comparedate(evt) { // preventing default behavior (form submit in this case) evt.preventDefault();
// here we translate 'string' value back to 'date' & extract year var yearOfBirth = new Date(borndate.value).getFullYear() // an alternative would be to simply parse the year off the string itself
if (yearOfBirth >= todaysYear) { alert("Looks like you are to young!"); } else { // submitting form programmatically form.submit() }}
<div class="form"> <form class="login-form" method="POST" action="main.php"> <input type="date" id="borndate" name="borndate" required="required" /> <input type="submit" class="button" name="button" value="submit" /> </form></div>
Comparing two dates in jquery script
It is checking for object equality. Compare the time instead.
$(function(){ var d1 = new Date("2001-12-01"); var d2 = new Date("2001-12-01"); console.log(d1.getTime() == d2.getTime());});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
How can i compare two dates - they should match on day or year
You can try this
var date1 = moment(new Date(2019, 4, 17).valueOf()).format('MM/DD');
var date2 = moment(new Date(2019, 4, 17).valueOf()).format('MM/DD');
if (date1 === date2)
console.log('true');
else
console.log('false');
Compare two dates in cypress
They aren't modified as much as translated from your time zone (Central European Summer Time, is it?) to GMT. Your midnight is 10pm in Greenwich.
Considering that it happened to both dates, it doesn't change the result of the comparison.
If it nevertheless bothers you, there's Cypress' clock
function to influence how it handles, among other things, Date objects.
https://docs.cypress.io/api/commands/clock
Comparing two dates in when one date is in a previous year
- Using the Native Date function in js
var obj = {
startDate1: "02/01/2020",
endDate1: "03/01/2020",
startDate2:"02/05/2020",
endDate2:"02/15/2020"
};
// Create a clone of obj object and convert values to timestamp.
var $dates = {};
$dates.startDate1 = new Date(obj.startDate1).getTime();
$dates.startDate2 = new Date(obj.startDate2).getTime();
$dates.endDate1 = new Date(obj.endDate1).getTime();
$dates.endDate2 = new Date(obj.endDate2).getTime();
- Comparing time:
if (($dates.endDate1 >= $dates.startDate2 && $dates.startDate1 <= $dates.endDate2) ||
($dates.endDate2 >= $dates.startDate1 && $dates.startDate2 <= $dates.endDate1)) {
// etc...
}
Related Topics
Equivalent of Jquery .Hide() to Set Visibility: Hidden
Difference Between "Let" and "Var"
How to Loop Through or Enumerate a JavaScript Object
How to Include a JavaScript File in Another JavaScript File
From an Array of Objects, Extract Value of a Property as Array
Accessing Nested JavaScript Objects and Arrays by String Path
Why Is Using "For...In" For Array Iteration a Bad Idea
How to Convert an Existing Callback API to Promises
How to Include CSS and Jquery in My Wordpress Plugin
Self-References in Object Literals/Initializers
How to Find Documentation on Formatting a Date in JavaScript
Es6 Modules in the Browser: Uncaught Syntaxerror: Unexpected Token Import
Detect a Finger Swipe Through JavaScript on the Iphone and Android