JavaScript Objects: Dates - The GetDate() Method
(Page 4 of 5 )
Here is a method you nerds could really use. Don't get your hopes up though; it isn't used to get you that kind of date. It is used to extract the day of the month. Here it is in some perty code:
<html>
<body>
<script type="text/javascript">
var when = new Date()
document.write(when.getDate())
</script>
</body>
</html>
This example creates a new variable named "when." It then uses the GetDate() method to extract today's date from the variable (which we filled with data from the Date() function).
The result is:
28
The GetDay() Method
The GetDay() method allows us to see what day of the week it is, in numeric form. It is coded like this:
<html>
<body>
<script type="text/javascript">
var when = new Date()
document.write("Today is this day of the week:")
document.write(when.getDay())
</script>
</body>
</html>
This would result in:
Today is this day of the week:
4
Note that Sunday is the 0 day of the week, so 4 would be Thursday.
Now what if we wanted to create a more helpful program that went ahead and told us the day of the week with a word, so we didn't have to use our brain? Well, we could do it this way:
<html>
<body>
<script type="text/javascript">
var when=new Date()
var whatday=new Array(7)
whatday[0]="Sunday!"
whatday[1]="Monday!"
whatday[2]="Tuesday!"
whatday[3]="Wednesday!"
whatday[4]="Thursday!"
whatday[5]="Friday!"
whatday[6]="Saturday!"
document.write("The day of the week is... " + whatday[when.getDay()])
</script>
</body>
</html>
This would print out:
The day of the week is...Thursday!
Next: The GetMonth() Method >>
More JavaScript Articles
More By James Payne