roosterup
asked on
Compare two mmddyyyy dates in JavaScript
I need to compare two dates in JavaScript that are entered as MMDDYYYY and throw an error if one is before the other.
In the .js file, any chars are stripped out from the two fields.
var cmDateOfInjury = stripCharsNotInBag (form.cmDateOfInjury.value , "1234567890");
form.cmDateOfInjury.value = cmDateOfInjury;
var cmDateNotify = stripCharsNotInBag (form.cmDateNotify.value, "1234567890");
form.cmDateNotify.value = cmDateNotify;
The cmDateNotify cannot be before the cmDateOfInjury. How do I convert the dates and compare?
In the .js file, any chars are stripped out from the two fields.
var cmDateOfInjury = stripCharsNotInBag (form.cmDateOfInjury.value
form.cmDateOfInjury.value = cmDateOfInjury;
var cmDateNotify = stripCharsNotInBag (form.cmDateNotify.value, "1234567890");
form.cmDateNotify.value = cmDateNotify;
The cmDateNotify cannot be before the cmDateOfInjury. How do I convert the dates and compare?
Are the dates exactly like MMDDYYYY i.e. no seperators?
I'd jiggle with the strings first.
Make them in the form yyyymmdd and then do an integer compare.
eg
Make them in the form yyyymmdd and then do an integer compare.
eg
<script>
var doi = "12252013";
var don = "12302013";
doi = doi.substring(4) + doi.substring(0, 4);
don = don.substring(4) + don.substring(0, 4);
if(parseInt(don) < parseInt(doi))
document.write("invalid, notify date cannot be earlier");
else
document.write("this is ok");
</script>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Yes, the dates are MMDDYYYY with no separators.
lsavidge has given you a nice easy solution for your case then.
ASKER
awesome.
Thanks :)
Whenever playing dates and you're doing a date comparison, I always and I mean I ALWAYS, convert to an integer and compare. It's a lot easier to do in code. Put some comments in the code because sometimes it may be a bit weird to someone that doesn't use this method.
It makes sorting lists of dates a doddle as well.
Whenever playing dates and you're doing a date comparison, I always and I mean I ALWAYS, convert to an integer and compare. It's a lot easier to do in code. Put some comments in the code because sometimes it may be a bit weird to someone that doesn't use this method.
It makes sorting lists of dates a doddle as well.