Using the Date() Object to Create a Clock - A Useful Date Format Example
(Page 4 of 4 )
Here is a quick and simple way to just display the date:
<script type="text/javascript">
document.write(Date())
zzzzz</script>
That is all very well, as now we have a date displayed. For the final part of this tutorial, however, an example of further formatting will be shown for the date display. First, the date can be further formatted for clarity. For example, rather than display a date as 27-08-07, why not state the month by displaying 27-August-2007. This can be accomplished by using arrays and the getmonth() function.
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
var months = new Array("January", "February", "March", "April",
"May", "June", "July", "August", "September", "October",
"November", "December");
var today = new Date();
var thedate = today.getDate();
var themonth = today.getMonth();
var theyear = today.getFullYear();
document.write(thedate + "-" + months[themonth] + "-" +
theyear);
//-->
</SCRIPT>
Script coders will remember the array format and how it is used. In case there is some revision needed here, there is a variable called months used to contain the months of the year. The variable called months is created to store the months of the year in the array constructor. To point at the month names in the array, the code uses getMonth().
For example, getMonth would return the digit 7 for August. So in the final line where it states months[themonth], for August, themonth=7. The array does its work here by becoming months[7] and that array location points to August. Hold on, that is the number 7. Surely, August is the eighth month of the year! But remember how arrays handle numbers; they begin counting from 0 and not 1.
This concludes the overview of the date() object and some useful tips on how it can be used. It is always a nice touch to insert a live time display and date on a web page.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |