Reputation: 1849
Good afternoon in my timezone.
I want to compare two dates , one of them is inserted by the user and the other is the present day. Snippet of code :
var dateString = "2012-01-03"
var date = new Date(dateString);
date < new Date() ? true : false;
This returns true, i think under the hood both Date objects are transformed to milliseconds and then compared , and if it is this way the "Today" object is bigger because of the hours and minutes.So what i want to do is compare dates just by the day month and year.What is the best approach ? Create a new Date object and then reset the hours minutes and milliseconds to zero before the comparison? Or extract the day the month and year from both dates object and make the comparison ? Is there any better approach ?
Thanks in advance With the best regards. Happy new year
Upvotes: 11
Views: 24748
Reputation: 2742
A production-ready example based on top of Accepted Answer
Add the following function to your Javascript
Date.prototype.removeTimeFromDate = function () { var newDate = new Date(this); newDate.setHours(0, 0, 0, 0); return newDate; }
Invoke it whenever you wish to compare
firstDate.removeTimeFromDate() < secondDate.removeTimeFromDate()
Upvotes: 0
Reputation: 32532
Since it's in yyyy-mm-dd format, you can just build the current yyyy-mm-dd from date object and do a regular string comparison:
var currentDate = new Date();
var year = currentDate.getFullYear();
var month = currentDate.getMonth()+1;
if (month < 10) month = "0" + month;
var day = currentDate.getDate();
if (day < 10) day = "0" + day;
currentDate = year + "-" + month + "-" + day;
var dateString = "2012-01-03"
var compareDates = dateString < currentDate ? true : false;
document.write(compareDates);
Upvotes: 0
Reputation: 207491
Set the time portion of your created date to zeros.
var d = new Date();
d.setHours(0,0,0,0);
Upvotes: 30