Create a Website
HTML
Dreamweaver
CSS Tutorial
JavaScript
FREE Domain!
Any web hosting you subscribe with DotEasy will get you a FREE domain name registration.
PLUS you get:
  • FREE Website Builder
  • FREE Blog
  • FREE Forum
  • FREE Photo Album
  • FREE Email Accounts
Get your FREE domain name today!
Home > JavaScript Tutorial
SSD Web Hosting with FREE Domain

The Date object is used to work with dates and times.

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("" + day + "/" + month + "/" + year + "")

Results in this...

Displaying the Current Time

Typing this code...

The following code line:

var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10)
minutes = "0" + minutes
document.write("" + hours + ":" + minutes + " " + "")

will result in the following output:

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("" + hours + ":" + minutes + " " + suffix + "")

will result:

Enjoy this tutorial?

1. Link to this page(copy/paste into your own website or blog):
2. Add this page to your favorite social bookmarks sites:
3. Add this page as your favorites. (Press Ctrl+D)