Javascript
  1. Javascript intro
  2. Javascript basics
  3. Javascript variables
  4. Javascript functions
  5. Javascript popup boxes
  6. Javascript conditions
  7. Javascript loops
  8. Javascript arrays
  9. Javascript objects
  10. Javascript strings
  11. Javascript events
  12. Javascript errors
  13. Javascript DOM
  14. Javascript elements
  15. Javascript new windows
  16. Javascript date & time
  17. Javascript cookies
  18. Javascript print
  19. Javascript redirect
  20. Javascript void
  21. Javascript summary

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 correct 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 tutorial 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

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:

Example:
<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:

Example:
<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:

Example:
<script type="text/javascript"> document.write("Date and time: " + Date()); </script>
Output:
© Copyright 2013-2014 Landofcode.com
Terms of use | Privacy policy | Copyright information