Reputation: 3064
I'm working with javascript Date and i'm starting to go crazy :)
I want two compare only the year,month, day of two dates. The date are (retrieve from firebug stacktrace):
[Date {Thu Feb 11 2010 12:00:00 GMT+0000 (GMT Standard Time)}]
[Date {Sun Jul 11 2010 00:00:00 GMT+0100 (GMT Daylight Time)}]
In this point i'm trying compare the two dates like this:
if (datepickerBegin == null || datepickerBegin.length == 0 || datepickerBegin != date) {
//Do stuff
}
This code obvious doesn't work, which is the simple way of comparing these two String?
I'm trying to convert this var to Date and concatenate into another var the getMonth()+getYear()+getDay()
... but
i believe that there is a easiest way.
By the way, why the following line give NaN
new Date(datepickerBegin).getMonth()
but the following line works?
new Date(Date.parse(datepickerBegin.toString())).getMonth()
Upvotes: 0
Views: 249
Reputation: 962
After parsing the dates using Date.parse(...);
, you can use the Date constructor to create date types like so. An example of this process has been abstracted into the function below:
function parseDateAsDatePart(dateString) {
var parsedDate = new Date(Date.parse(dateString));
return new Date(parsedDate.getYear(), parsedDate.getMonth(), parsedDate.getDate());
}
Once you change both strings into Date objects, you may compare them as shown above.
Note: as Linus mentioned above, Date.parse(...)
returns an integer, not a date object, so it needs to be wrapped in the Date constructor.
Upvotes: 2
Reputation: 29559
Try converting the dates to time, using the .getTime()
method. If the dates are equal, they will have the same values returned from getTime. This assumes that you're only using string values for your dates (ie "9/6/12"). If your dates will have time stamps associated with them, then you'll need to use the setHours()
function to set all the time reference to 0 (d.setHours(0,0,0,0);
).
Links:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTime
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setHours
Example:
if(datePickerBegin.getTime() === datePickerEnd.getTime())
{
//...do something.
}
Note: If you do end up going the .getMonth()
route, then be aware that the function returns the months as zero based numbers, so add 1 to what it returns.
Upvotes: 1
Reputation: 29000
You can try with getMonth, GetDays , ...
http://www.comptechdoc.org/independent/web/cgi/javamanual/javadate.html
Upvotes: 0