Quackit Logo
FREE Hosting!
With every domain you register with ZappyHost you get FREE hosting.
Create free Flash websites

JavaScript Date and Time

Print Version

JavaScript provides you with the ability to access the date and time of your users' local computer, which can be quite useful at times. Displaying the current date and time in a nice user friendly way using JavaScript is not quite as simple as you might like. You need to massage the data a little. You can do this using a bunch of JavaScript date and time functions.

Displaying the Current Date

Typing this code...

  var currentDate = new Date()
  var day = currentDate.getDate()
  var month = currentDate.getMonth()
  var year = currentDate.getFullYear()
  document.write("<b>" + day + "/" + month + "/" + year + "</b>")

Results in this...

Displaying the Current Time

Typing this code...

  var currentTime = new Date()
  var hours = currentTime.getHours()
  var minutes = currentTime.getMinutes()

  if (minutes < 10)
  minutes = "0" + minutes

  document.write("<b>" + hours + ":" + minutes + " " + "</b>")

Results in this...

You may have noticed that we had to add a leading zero to the minutes part of the date if it was less than 10. By default, JavaScript doesn't display the leading zero. Also, you might have noticed that the time is being displayed in 24 hour time format. This is how JavaScript displays the time. If you need to display it in AM/PM format, you need to convert it.

Displaying the Current Time in AM/PM Format

Typing this code...

  var currentTime = new Date()
  var hours = currentTime.getHours()
  var minutes = currentTime.getMinutes()

  var suffix = "AM";
  if (hours >= 12) {
  suffix = "PM";
  hours = hours - 12;
  }
  if (hours == 0) {
  hours = 12;
  }

  if (minutes < 10)
  minutes = "0" + minutes

  document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")

Results in this...

JavaScript Date and Time Functions

For a full list of JavaScript date and time functions, see JavaScript Date and Time Functions

Enjoy this website?

  1. Add this page to your Favorites
  2. Link to this page (copy/paste into your own website or blog):
  3. Help support Quackit by making a donation

Oh, and thank you for supporting Quackit!

Need Website Content?
Get unique, quality digital content for your website.
  • 270+ Website Templates
  • 800+ Flash Templates
  • 25,000+ Images, Logos
  • 30,000+ e-Books
  • 15,000+ Scripts
  • 27,000+ Animated GIFs
  • 21,000+ Ringtones
  • ...and much more!
Get your content now!
$1.99 .info domain names!
© Copyright 2000 - 2010 Quackit.com