Today's Date
JavaScript can automatically detect the current date, using the Date() function. If you wanted to be able to tell your Web-viewers what the date is, just use this code:
<script language="JavaScript">
var today = new Date();
document.write((today.getMonth() + 1) + " / " + today.getDate() + " / " + today.getFullYear() + "<br />");
</script>
|
Here is a basic breakdown of what each part means:
- todaythe variable that will contain our date information
- newcreates an empty object for storing information; in this case, that object is a date
- Date()declares the new object as a date; the empty parentheses initialize the date object with the current date information
- (.getMonth() + 1)this function give us the current month; the entire expression is in parentheses with + 1 included because the .getMonth() gives you a number between 0 and 11 ("0" being January, and "11" being December), so you have to add 1 to the number returned by the function to display the standard numeric months
- .getDate()this function give us the current day of the month
- .getFullYear()this function give us the current year, displaying the entire 4-digit year instead of the 2-digit year (a good thing to do, since Y2K issues could affect the output or calculations based on the date)
The above lines of code will create the following display:
|