VBScript Date Functions - Functioning it Up with CDate
(Page 2 of 4 )
The CDate function allows the user to check if a value can be converted to a date or time. It can also be used to do the actual conversion. Here is an example that converts a string to a date:
<html>
<body>
<script type="text/vbscript">
birthdate="April 22 1977"
if IsDate(birthdate) then
document.write(CDate(birthdate))
end if
</script>
</body>
</html>
The result of this program would be:
4/22/1977
Note that in the above example the valid date could be converted. But what if it couldn't? Try changing the code to show birthdate= "Afrail 10 2BD0." You will notice that there is no output; that is because the value cannot be converted to a date. Ideally, we would want to let the user know that the value is invalid. Here is how we would do so:
<html>
<body>
<script type="text/vbscript">
birthdate="Afrail 22 1977"
if IsDate(birthdate) then
document.write(CDate(birthdate))
else
document.write("That value cannot be converted")
document.write("<p>The pain train is coming. Whoo! Whoo!</p>")
end if
</script>
</body>
</html>
Because the value is invalid, and we added an else clause, this results in the text:
That value cannot be converted
The pain train is coming. Whoo! Whoo!
You can also convert numbers to a date, like so:
<html>
<body>
<script type="text/vbscript">
releasedate=#12/22/2007#
if IsDate(releasedate) then
document.write(CDate(releasedate))
end if
</script>
</body>
</html>
Or
<html>
<body>
<script type="text/vbscript">
releasedate=#12 22 2007#
if IsDate(releasedate) then
document.write(CDate(releasedate))
end if
</script>
</body>
</html>
And lastly, you can convert a value to time in the following manner:
<html>
<body>
<script type="text/vbscript">
witchinghour="12:00:00 AM"
if IsDate(witchinghour) then
document.write(CDate(witchinghour))
else
document.write("That isn't the witching hour you fool!")
end if
</script>
</body>
</html>
Next: Working with the Date Function >>
More BrainDump Articles
More By James Payne