Useful Web Widgets - Getting Down With Father Time
(Page 2 of 5 )
Keeping track of time and things that require time is pretty important for people these days. Even visitors to your site that have a watch on their wrist may find it valuable to see the time and date displayed somewhere on your pages. JavaScript has quite a few functions that deal with dates and times but their output is not always what you may need for display. The next script uses the built in JavaScript date and time functions to produce a displayable date and time in any format you want.
This function uses a specially formatted string to determine what format to display. The rules are pretty simple. Below is a sample string.
"ts,dl,l"
The string has a comma separated structure with two sections of two letters each and a single section of one character. The first character in the two character sections can be either a "t" or "d". The "t" stands for "text" and indicates that the month or day will be expressed in text. The "d" stands for "digit" and will render the month or day as a digit. The second character in the two character sections can be either an "s" or "l". The "s" stands for short which would mean that the short form of the value would be displayed such as "Aug" or "Wed". The "l" stands for "long" and would render a long version of the month or day such as "August" or "Wednesday" The single character section can contain either a "s" or an "l" to render either a short or long version of the year (06 or 2006).
Given this, the sort of date we could derive from the above example would look like this.
Jan 01 2006
The month is text and in short form and the day is exclusively in digits in long form (leading zero). The year is displayed in long form as well. The format we are working with here is standard US month, day, year. The function could be reworked for other date formats as well.
If the day is specified to be text in long form, it is rendered in both digit form and text as follows.
Sunday Jan 01 2006
By using this method you can display many formats under script control.
Next: The Function in Depth >>
More JavaScript Articles
More By Chris Root