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")
method | example | result | Note |
---|---|---|---|
getDay() | picoBarkday.getDay() | 1 | Day of Week, Sunday is day 0 |
getDate() | picoBarkday.getDate() | 20 | Day of Month |
getMonth() | picoBarkday.getMonth() | 11 | Programmers count from 0, so this is December |
getFullYear() | picoBarkday.getFullYear() | 1999 | 4 Digit Year |
getTime() | picoBarkday.getTime() | e.g. 945673200000 | JavaScript 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