spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / js / scripts / basic_date

Applications Developer - Sharepoint
Professional Technical Resources
US-OR-Portland

Justtechjobs.com Post A Job | Post A Resume
Developer News
Microsoft Shows Some Ankle With Visual Studio
Gentoo Linux Cancels Distribution
It's Official: Windows 7 at PDC, WinHEC

JavaScript: Basic Date Display Script

By Lee Underwood

Have you been wanting to display the current date on your Web pages? There are several ways to accomplish it. One method uses JavaScript, and the good news is that you don't have to write the script from scratch. There are many sites that offer existing JavaScripts, such as JavaScript Source and Script Search. These scripts are usually provided free of charge.

The very thought of using JavaScript scares many people, although it shouldn't. When using an existing script, it usually doesn't take any programming knowledge to implement it. In our case, we have a ready-to-use basic date script, "right out of the box," thanks to our friends at cgiscript.net. This one even has comments so you can better understand how the script works.

The Basic Script

First, let's look at the script itself. For the sake of brevity, I've removed all the comments and extra lines. The fully documented file can be found at cgiscript.net.

<script language="JavaScript">
  <!--
    var now = new Date();
    var days = new Array(
      'Sunday','Monday','Tuesday',
      'Wednesday','Thursday','Friday','Saturday');
    var months = new Array(
      'January','February','March','April','May',
      'June','July','August','September','October',
      'November','December');
    var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
    function fourdigits(number)	{
      return (number < 1000) ? number + 1900 : number;}
    today =  days[now.getDay()] + ", " +
       months[now.getMonth()] + " " +
       date + ", " +
       (fourdigits(now.getYear()));
     document.write(today);
  //-->
</script>

The first and last two lines aren't part of the actual code. They tell the browser the type of language used in the script and use the HTML comment code to keep it from being viewed as text by older browsers. The script itself is quite simple. The first part declares four variables: now, days, months, and date. The function fourdigits is then declared, which sets up the display of the year. Next, the four lines shown in red specify the display format and the last line, shown in blue, tells the script to print the information on the Web page.

Formatting the Date

As it's written in the script, the date is displayed on the Web page in the following format: Wednesday, January 05, 2005. This is accomplished as follows, using the code shown above in red:

The display format can be changed by making a few modifications in the lines shown in red. For instance, in order to change the display to January 05, 2005 (Wednesday), the code would be modified as shown in the box below. Notice that the only modification is in the last line. We moved it from the beginning to the end of our statement and added the parentheses.

  today =  months[now.getMonth()] + " " +
    date + ", " +
    (fourdigits(now.getYear())) + " " +
    "("+days[now.getDay()]+")";

If you want to display just the date, without the day of the week, you can modify the code as shown below:

  today =  months[now.getMonth()] + " " +
    date + ", " +
    (fourdigits(now.getYear()));

Placement of the Script

There are two general methods used to place the script on the Web page. The one given by the folks at cgiscript.net places the script in the body of the document where it is to be displayed. Another, less confusing method would be to place the script in an external file and call it from within the page where you want it displayed. This method would save space and makes it easier to call the script from other pages, as well.

First, copy the script itself, without the opening and closing script and comments tags, and put it into a blank file. Then give the file a name, such as "date.js." It should look like the one in the box below (the last few lines may look different if you have made changes to the display format).

// ***********************************************
// AUTHOR: WWW.CGISCRIPT.NET, LLC
// URL: http://www.cgiscript.net
// Use the script, just leave this message intact.
// Download your FREE CGI/Perl Scripts today!
// ( http://www.cgiscript.net/scripts.htm )
// ***********************************************
      var now = new Date();
      var days = new Array(
        'Sunday','Monday','Tuesday',
        'Wednesday','Thursday','Friday','Saturday');
      var months = new Array(
        'January','February','March','April','May',
        'June','July','August','September','October',
        'November','December');
      var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
        function fourdigits(number)	{
          return (number < 1000) ? number + 1900 : number;}
      today =  days[now.getDay()] + ", " +
        months[now.getMonth()] + " " +
        date + ", " +
          (fourdigits(now.getYear()));
      document.write(today);

To call the script, place a link to the file you just created on the Web page where you want the date displayed. The link should look like this: <script language="JavaScript" src="date.js"></script> Be sure there are no spaces or code between the opening and closing <script> tags as this may cause the loading of the script to fail.

Conclusion

That's all there is to it. We'll look at some other simple scripts in the future and see how to use them. In the meantime, if you have problems with other scripts, be sure to check out our JavaScript section and our forum.

home / js / scripts / basic_date



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES
webref The latest from WebReference.com Browse >
Controllers: Programming Application Logic - Part 2 · How to Use JavaScript to Validate Form Data · Controllers: Programming Application Logic
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Sprint Launches Mobile WiMAX Network · Albatron Downsizes with the KI780G Mini-ITX Motherboard · Can't Find a Wi-Fi Network? Make Your Own.

Created: January 10, 2005

URL: http://webreference.com/js/scripts/basic_date/