Introduction to the JavaScript Date Object

Introduction to the JavaScript Date Object
If you aren't at all familiar with Objects and Methods, you may want to start with my article document.write("Hello World") and other cases of something-dot-somethingelse.

One of the most useful JavaScript objects, particularly for beginners or people looking to add some simple context sensitivity to their webpages is the Date() object. The Date() object is a native built-in object, which means that it is available by default in all JavaScript implementations. You can count on it being there and you don't have to tell your program that you are going to use it.

The simplest thing to do with the date object is just use it to display the current date in the default format.

document.write(Date()) gives

This isn't necessarily how you'd want to format the date on a letter to your mom, but it works well for putting a date in the footer of a web page or dating your latest news update – in fact, if you look around on the web, it's not uncommon to see dates in this form. (The exact format will vary depending on the locale settings on the computer where this is run.) It's an easy way to make your page always look current (as long as you make sure that the content that goes with it isn't obviously outdated!)

To do more with dates, you need to create your own instance of the date object. For instance, var now = new Date() to set it to the current date and time or var picoBarkday = new Date("December 20, 1999") to set it to a specific date. (Note: both now and picoBarkday are variables I chose.) Once we have our own date object, we can use different Date methods to change or find information about the date.

For the following examples, we set Pico's birthday as follows:
var picoBarkday = new Date("December 20 1999")

methodexampleresultNote
getDay()picoBarkday.getDay()1Day of Week, Sunday is day 0
getDate()picoBarkday.getDate()20Day of Month
getMonth()picoBarkday.getMonth()11Programmers count from 0, so this is December
getFullYear()picoBarkday.getFullYear()19994 Digit Year
getTime()picoBarkday.getTime()e.g. 945673200000JavaScript actually keeps track of time in Milliseconds since January 1st, 1970, this is that number


You can see these examples live and get the code here


This site needs an editor - click to learn more!


You Should Also Read:
Basic Intro to Objects and Methods
A First JavaScript Program
JavaScript/Java Newsletter

RSS
Related Articles
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Julie L Baumler. All rights reserved.
This content was written by Julie L Baumler. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.