Javascript
JS intro
JS basics
JS variables
JS functions
JS popup boxes
JS conditional logic
JS loops
JS arrays
JS objects
JS strings
JS events
JS errors
JS DOM
JS elements
JS new windows
JS date and time
JS cookies
JS print
JS redirect
JS void 0
JS Summary

Programming

Programming intro
Java

Markup

First webpage guide
HTML
XHTML

Style & Layout

CSS

Browser scripting

VBScript
AJAX

Server scripting

PHP
ASP

Making money online

Make money online

Javascript date and time

Javascript provides the functionality to display date and time on a webpage.

NOTE: Whenever you display the time or date on a webpage using Javascript, it will get that data from whatever the user has on their computer, whether it is incorrect or not. So if the current date and time is January 15th 12:30, but the users computer is set to January 10th 8:30, that is what will be displayed.

This lesson focuses on:

The Date object

The Date object is used to display date and time on a webpage.

Defining a Date object

Example:

var D = new Date();

NOTE: The Date object stores the current date and time by default.

Date object methods

getDate();

Returns the day of the month in numerical form (1 - 31)

getDay();

Returns the day of the month in numerical form (0 - 6)

getHours();

Returns the current hour (0 -23)

getMinutes();

Returns the current minute (0- 59)

getSeconds();

Returns the current seconds (0 - 59)

Displaying a date on a webpage

You can display a date on a webpage using the appropriate methods of the Date object needed to do this:

<script type="text/javascript">
var D = new Date();

var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getFullYear();
var date = month + "/" + day + "/" + year;

document.write("Current date:" + date);
</script>

Output:


Displaying time on a webpage

You can display time on a webpage using the appropriate methods of the Date object needed to do this:

<script type="text/javascript">
var D = new Date();
var hours = D.getHours();
var minutes = D.getMinutes();
var seconds = D.getSeconds();
var time = hours + ":" + minutes + ":" + seconds;

document.write("The time is now " + time);
</script>

Output:


Displaying date and time on a webpage

You can display the current date and time together on a webpage using just the Date object without any methods since the Date object stores the current date and time by default:

<script type="text/javascript">
document.write("Date and time: " + Date());
</script>

Output:


Practice

Online code editor
Practical examples
Practical exercises
Step-by-step tutorials

Reference

Terms glossary
Reference material

Rate this site

Rate this site
Visitor comments