I have the following :
var fit_start_time = $("#fit_start_time").val(); //2013-09-5
var fit_end_time = $("#fit_end_time").val(); //2013-09-10
if(Date.parse(fit_start_time)>=Date.parse(fit_end_time)){
alert("Please select a different End Date.");
}
The above code doesn't work. Is there any other solution to the above one?
formatting date as per Where can I find documentation on formatting a date in JavaScript? also dint work for me.
It's quite simple:
if(new Date(fit_start_time) <= new Date(fit_end_time))
{//compare end <=, not >=
//your code here
}
Comparing 2 Date
instances will work just fine. It'll just call valueOf
implicitly, coercing the Date
instances to integers, which can be compared using all comparison operators. Well, to be 100% accurate: the Date
instances will be coerced to the Number
type, since JS doesn't know of integers or floats, they're all signed 64bit IEEE 754 double precision floating point numbers.
To comapre dates of string format (mm-dd-yyyy).
var job_start_date = "10-1-2014"; // Oct 1, 2014
var job_end_date = "11-1-2014"; // Nov 1, 2014
job_start_date = job_start_date.split('-');
job_end_date = job_end_date.split('-');
var new_start_date = new Date(job_start_date[2],job_start_date[0],job_start_date[1]);
var new_end_date = new Date(job_end_date[2],job_end_date[0],job_end_date[1]);
if(new_end_date <= new_start_date) {
// your code
}
As in your example, the fit_start_time
is not later than the fit_end_time
.
Try it the other way round:
var fit_start_time = $("#fit_start_time").val(); //2013-09-5
var fit_end_time = $("#fit_end_time").val(); //2013-09-10
if(Date.parse(fit_start_time) <= Date.parse(fit_end_time)){
alert("Please select a different End Date.");
}
Update
Your code implies that you want to see the alert
with the current variables you have. If this is the case then the above code is correct. If you're intention (as per the implication of the alert message
) is to make sure their fit_start_time
variable is a date that is before the fit_end_time
, then your original code is fine, but the data you're getting from the jQuery .val()
methods is not parsing correctly. It would help if you gave us the actual HTML which the selector is sniffing at.
try with new Date(obj).getTime()
if( new Date(fit_start_time).getTime() > new Date(fit_end_time).getTime() )
{
alert(fit_start_time + " is greater."); // your code
}
else if( new Date(fit_start_time).getTime() < new Date(fit_end_time).getTime() )
{
alert(fit_end_time + " is greater."); // your code
}
else
{
alert("both are same!"); // your code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With