Place your message here

Your Guide to Professional
Web Site Design and Development

Web Development
HTML Codes
HTML Tips
Javascript Snippets
216 Safe Colors
Symbols
Web Directory
Web Resources
Internet Channels

Web Development: Business, Advertising, Internet Marketing, Promotion and Web Site Design

| Web Development | HTML Codes | HTML Tips | Javascript Snippets | 216 Safe Colors | Symbols | Recommendations |

Basic JavaScript Date and Time Functions

By William Bontrager

As the title implies, this tutorial will show you how to get the date and time from the visitor's computer and print them to the web page.

You'll learn two basic techniques:

1. How to create what's called a date object.

2. How to extract information from that date object; the hour, minute, month, year, and so forth.

A complete working example of what you'll learn here is near the end of this tutorial.

How To Create What's Called a Date Object

When a date object is created, it is stored in what's called a variable. A variable is simply the name of a place in memory that can contain information. In our example, we'll call that variable "now" because it's a good name for the current date and time.

This is how you create a date object and store it in a variable:

var now = new Date();

The "new Date()" part of the above statement creates the date object. The "var now =" part causes the date object to be stored in the variable named "now".

How To Extract Information From that Date Object

Lots of information can be extracted from a date object. In this tutorial, we'll extract only what we'll need:

var hour        = now.getHours();
var minute      = now.getMinutes();
var second      = now.getSeconds();
var monthnumber = now.getMonth();
var monthday    = now.getDate();
var year        = now.getYear();

Notice that the name of the variable containing the date object and a period are followed by the function name. The function extracts the information from the date object and stores it in the variable named on the left of the equal sign.

All of the function names are intuitive except getDate(), which gets the day of the month rather than a date. Do not confuse "getDate()" with "new Date()" -- the former, as stated, extracts the day of the month from a date object. The latter creates the date object itself.

Printing the Date and Time

The example near the end of this tutorial demonstrates one method of obtain the date and time and printing it on a web page.

The Date

To get the date, the complete working example further below has a function called getCalendarDate()

The first 13 lines of the function creates an array containing the names of the calendar month. The value obtained from the now.getMonth() function is used to determine which month name to use. The line that does that is

var monthname = months[monthnumber];

When now.getMonth() extracts a month number, it assumes January is number 0 and December is number 11. If you prefer to print the number of the month instead of the name of the month, replace the above line with

monthnumber = monthnumber + 1;

to conform the month number with the way most humans count them (January = 1, etc.).

The getCalendarDate() function also has a line to adjust the year if the visitor is using an older browser that still assumes we're living in the 1900's. You'll recognize the line when you read the code.

getCalendarDate() constructs a string of characters representing the calendar date. It then returns that construction to whatever JavaScript code calls the function.

The Time

To get the time, the complete working example further below has a function called getClockTime() getClockTime() includes code to format the clock time into an "AM" or "PM" representation. The following four lines accomplish that.

var ap = "AM";
if (hour   > 11) { ap = "PM";        }
if (hour   > 12) { hour = hour - 12; }
if (hour   == 0) { hour = 12;        }

If you want the clock time to represent a 24-hour clock instead of an "AM/PM" representation, simply remove those four lines from the function.

getClockTime() constructs a string of characters representing the clock time. It then returns that construction to whatever JavaScript code calls the function. If you don't want the construction to include the "AM" or "PM" part, remove the last two lines from the code that constructs the clock time.

The Printing

To print the date and time, use JavaScript to call the getCalendarDate() and getClockTime() functions. Then print the strings of characters they return. Example:

<script type="text/javascript" language="JavaScript"><!--
var calendarDate = getCalendarDate();
var clockTime = getClockTime();
document.write('Date is ' + calendarDate);
document.write('<br>');
document.write('Time is ' + clockTime);
//--></script>

The Complete Working Example

Here is a web page that incorporates everything this tutorial has mentioned.

Note that JavaScript is line break sensitive. Thus, it's best to keep the lines as they are, at least until you are ready to do custom modifications.

<html>
<head>

<script type="text/javascript" language="JavaScript">
<!-- Copyright 2002 Bontrager Connection, LLC

function getCalendarDate()
{
   var months = new Array(13);
   months[0]  = "January";
   months[1]  = "February";
   months[2]  = "March";
   months[3]  = "April";
   months[4]  = "May";
   months[5]  = "June";
   months[6]  = "July";
   months[7]  = "August";
   months[8]  = "September";
   months[9]  = "October";
   months[10] = "November";
   months[11] = "December";
   var now         = new Date();
   var monthnumber = now.getMonth();
   var monthname   = months[monthnumber];
   var monthday    = now.getDate();
   var year        = now.getYear();
   if(year < 2000) { year = year + 1900; }
   var dateString = monthname +
                    ' ' +
                    monthday +
                    ', ' +
                    year;
   return dateString;
} // function getCalendarDate()

function getClockTime()
{
   var now    = new Date();
   var hour   = now.getHours();
   var minute = now.getMinutes();
   var second = now.getSeconds();
   var ap = "AM";
   if (hour   > 11) { ap = "PM";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (hour   < 10) { hour   = "0" + hour;   }
   if (minute < 10) { minute = "0" + minute; }
   if (second < 10) { second = "0" + second; }
   var timeString = hour +
                    ':' +
                    minute +
                    ':' +
                    second +
                    " " +
                    ap;
   return timeString;
} // function getClockTime()

//-->
</script>

</head>
<body>

<script type="text/javascript" language="JavaScript"><!--
var calendarDate = getCalendarDate();
var clockTime = getClockTime();
document.write('Date is ' + calendarDate);
document.write('<br>');
document.write('Time is ' + clockTime);
//--></script>

</body>
</html>

That's the complete working example. Create a file with the example and load it into your browser.

Functions getCalendarDate() and getClockTime() can be used wherever you need to extract the calendar date or clock time. While outside the scope of this tutorial, those results can be used in status bars, form fields, and other locations such as the title bar and in applications with layers. The time can be continuously updated by repeatedly calling the getClockTime() and printing the latest results.
With the above example, you have the basics to build your own calendars and clocks.

Will Bontrager

About the Author:

William Bontrager Programmer/Publisher, "WillMaster Possibilities" ezine mailto:possibilities@willmaster.com

Are you looking for top quality scripts? Visit Willmaster and check out his highly acclaimed Master Series scripts. Some free, some for a fee.

Back