I have 2 variables. How can I compare the 2 variables in JavaScript to see if the dates are the same? I don't want to conevert the 2 dates with time. i just want to convert them into yyyy/dd/mm format.
var DateReported = "20/04/2011";
var StartDate = "16/04/2011";
I have to do something if StartDate < DateReported and something else if StartDate > DateReported
Thanks
If you have your dates stored as strings in the same date format, there's no reason why you can't you string comparison to check if they're equal:
var DateReported = "20/04/2011";
var StartDate = "16/04/2011";
return DateReported == StartDate; // returns false;
Update : if you actually need to compare the dates to determine which is the most recent, I'd recommend making use of a library - eg the jQuery UI module contains date handling code, so you can easily parse date strings:
var dReported = $.datepicker.formatDate('d/mm/yy', DateReported);
var dStarted = $.datepicker.formatDate('d/mm/yy', StartDate);
if (dReported > dStarted) { ... }
by == operator
if(DateReported == StartDate)
return true;
else create the date object and convert them to millisecond and then compare for > / <
DateReported = new Date(2011,4,20);
StartDate= new Date(2011,4,16);
if (DateReported .getTime()<StartDate.getTime()) {
alert('DateReported is less than StartDate');
}
If you don't want to use conversion to date, try this(I assume the months and days are always 0 padded):
var DateReported = "20/04/2011";
var StartDate = "16/04/2011";
var regExp = /(\d{2})\/(\d{2})\/(\d{4})/;
if
(
StartDate.replace(regExp, "$3$2$1") < DateReported.replace(regExp, "$3$2$1")
)
{
alert("Lesser");
}
else
{
alert("Greater");
}
Working Example: http://jsfiddle.net/GE83j/
Try this:
var DateReported = "20/04/2011";
var StartDate = "16/04/2011";
DateReported = new Date(DateReported).format("yyyy/dd/MM");
StartDate = new Date(StartDate).format("yyyy/dd/MM");
if (DateReported > StartDate) {
alert("Date Reported Greater");
}
else {
alert("Start Date Greater");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.