Click to See Complete Forum and Search --> : past date
nbenton99
01-07-2004, 11:57 AM
Hi I've been working on what should be a simple script I want to take a date and compare it with the current date and if it is in the past it is invalid.
Here's my code right now the date is hard coded but I would like to change it to be a variable. Does anyone see anything wrong with my code sometimes I think it's working and then it isn't.
<script>
today = new Date();
enteredDate = new Date("23/12/2004");
if (today < enteredDate){
alert("this date has past");
}
else{
alert("this is a good date");
}
</script>
TIA
Nikki
TheBearMay
01-07-2004, 12:03 PM
As you've constructed it enteredDate returns "Sat Nov 12 00:00 EST 2005" try using :
enteredDate = new Date("December 23, 2004");
nbenton99
01-07-2004, 12:29 PM
thanks but my problem then is that the users must enter the date as DD/MM/YYYY how can I do a compare with that?
TIA
Nikki
TheBearMay
01-07-2004, 12:50 PM
Not a problem:
var dVal="25/12/2004";
var monArr=["Jan","Feb","Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var dValDay = dVal.substring(0,2);
var dValMnth = dVal.substring(3,5);
var dValYr = dVal.substring(6,10);
var enteredDate2=monArr[dValMnth-1]+ " " + dValDay + ", " + dValYr;
enteredDate = new Date(enteredDate2);
nbenton99
01-07-2004, 01:01 PM
Is this right?
<script>
today = new Date();
//enteredDate = new Date("23/12/2004");
var dVal.value="25/12/2004";
var monArr=["Jan","Feb","Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dValDay = dVal.substring(0,2);
var dValMnth = dVal.substring(3,5);
var dValYr = dVal.substring(6,10);
var enteredDate2=monArr[dValMnth-1]+ " " + dValDay + ", " + dValYr;
enteredDate = new Date(enteredDate2);
if (today < enteredDate){
alert("this date has past");
}
else{
alert("this is a good date");
}
</script>
I'm still getting an error on the page.
TIA
Nikki
TheBearMay
01-07-2004, 01:03 PM
Ooops... My bad, I started to change the function after I tested it and didn't reset one of the changes. Remove the ".value" after dVal
Changed above also
nbenton99
01-07-2004, 01:08 PM
Thank you, it's working great now. I'm still trying to understand you code though, why the array and all the substrings. I'm assuming it's altering the format of the date.
Thanks
Nikki
TheBearMay
01-07-2004, 01:17 PM
I'm just picking apart (the substrings) the current date format and coverting it to a string in the form "Mmm dd, yyyy". The array was the easiest way I could think of to pull in the month as a text value quickly. Since it's a zero based array the value we want is 1 less than the month entered, i.e. monArr[0]=Jan. Thus enteredDate2 = "Dec 25, 2004"
nbenton99
01-07-2004, 01:21 PM
I see. Thank you for your help it is working beautifully now.
Thanks
Nikki