• Home

Logo

Navigation
  • Home
  • Articles
    • Content Writing
    • Design
    • General
    • Internet Marketing
    • Social Media
    • Tools and Tips
    • Usability
    • Web Hosting Articles
  • Tutorials
    • AJAX Tutorials
    • ASP Tutorials
    • C# Tutorials
    • CGI and Perl Tutorials
    • CSS Tutorials
    • Flash Tutorials
    • HTML Tutorials
    • Illustrator Tutorials
    • Java Tutorials
    • JavaScript Tutorials
    • Linux Tutorials
    • Miscellaneous Tutorials
    • MySQL Tutorials
    • Photoshop Tutorials
    • PHP Tutorials
    • Python Tutorials
    • Wireless Tutorials
    • WordPress Tutorials
    • XML Tutorials
  • Scripts
    • AJAX Scripts
    • ASP Scripts
    • ASP.NET Scripts
    • CGI & Perl Scripts
    • Flash Scripts
    • Java Scripts
    • JavaScript Scripts
    • PHP Scripts
    • Python Scripts
    • Remotely Hosted
    • Tools and Utilities
    • XML Scripts
  • Answers
  • Online Services
  • Tools

Basic JavaScript Date and Time Functions

By Will Bontrager | on Aug 12, 2004 | 0 Comment
JavaScript Tutorials
  • Tweet
  • Share
  • Tweet
  • Share

Basic JavaScript Date and Time Functions

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:

How to create what’s called a date object.

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.

Share this story:
  • tweet

Author Description

Publication: WillMaster Possibilities

No Responses to “Basic JavaScript Date and Time Functions”

You must be logged in to post a comment.

Connect With Us

RSSSubscribe 1,242Followers 492Likes
  • Popular
  • Recent
  • Comments
  • Creating Energy Spheres in Photoshop

    Apr 15, 2008 - 96 Comments
  • Easy Screen Scraping in PHP with the Simple HTML DOM Library

    Aug 6, 2008 - 20 Comments
  • Calculating date difference more precisely in PHP

    Mar 7, 2008 - 13 Comments
  • When Does Hosting Your Website in the Cloud Make Sense?

    Oct 8, 2010 - 2 Comments
  • Fun with the Microsoft Managed Extensibility Framework Part 2

    Oct 6, 2010 - 0 Comment
  • Fun with the Microsoft Managed Extensibility Framework Part 1

    Sep 22, 2010 - 0 Comment
  • Website Management on the go with the iPad

    I appreciated your post, but I was looking for something I didn't...
    November 24, 2012 - drmoderator
  • Creating Energy Spheres in Photoshop

    I'm a little stuck down here especially at the step of creating the...
    November 23, 2012 - sarah
  • Running background processes in PHP

    Can you give an example? As see it, you can use this only when you...
    November 16, 2012 - Shaked Klein Orbach
Developer Resources
  • Tutorial Directory
  • Learn HTML
  • Learn PHP
  • Learn CSS
  • Learn AJAX
  • Learn JavaScript
  • Learn Pear
  • White Papers
  • Resources
    • NetVisits Web Directory
    • Realtor Pixels
    • Answers On The Run
    • Ask A Geek
  • Recent Posts

    • When Does Hosting Your Website in the Cloud Make Sense?
    • Fun with the Microsoft Managed Extensibility Framework Part 2
    • Fun with the Microsoft Managed Extensibility Framework Part 1
    • Website Management on the go with the iPad
    • Code Contracts in C# 4.0 – Part 1

    Calendar

    May 2013
    M T W T F S S
    « Oct    
     12345
    6789101112
    13141516171819
    20212223242526
    2728293031  

    Recent Comments

    • drmoderator on Website Management on the go with the iPad
    • sarah on Creating Energy Spheres in Photoshop
    • Shaked Klein Orbach on Running background processes in PHP
    • Thomas Cuvillier on How To Upload Files Using PHP
    • rizal aditya on Extracting text from Word Documents via PHP and COM
    • Home
    © 2003 - 2013 DeveloperTutorials.com. All Rights Reserved. Privacy Policy.