Javascript: Date and Time
Although it's quite a specific thing to do – it's often very useful to get the date and time in Javascript.Date
Getting the current date (and manipulating it as necessary) in Javascript is very, very easy!There are three main functions that are necessary to do this, all of which are called on a date object. We can create a date object kind of like we create an array, using the 'new' keyword and then calling 'Date()' followed by a semicolon. So in this example we could do something like this:
var current = new Date();
Whenever you want to perform a function on an object- well firstly, it's not called a function anymore. A piece of code that get's executed on an object is called a method.
To perform a method on an object in Javascript, you can simply write the object name followed by the '.' operator, followed by the method name (and then any parameters it takes in brackets).
The first method we're interested in is "getDate" – this simply get's the number day (for example, today the day number is )).
The second method is "getMonth" which gets the number of the month. It's worth noting that it numbers them 0-11 though, so if your wanting to output the month – you'll want to add one to that (this month is number ).
The third method is "getFullYear" – this simply gets the year number (this year is ).
So if we wanted to output the whole date, we could do something like this:
var current = new Date(); var day = current.getDate(); var month = current.getMonth() + 1; var year = current.getFullYear(); document.write(day + '/' + month + '/' + year);
It would appear on the page like this:
Time
Getting the time is also extremely easy, and also uses methods of a date object!There are four main functions for getting the time, which are so simple I'm just going to present them to you in a linear fashion:
- "getHours()" – Current number of hours (0-23)
- "getMinutes()" – Current number of minutes (0-59)
- "getSeconds()" – Current number of seconds (0-59)
- "getTime()" - Number of milliseconds since 1/1/1970 at 12:00 am
So to make a simple clock, we could just use the first two ("getHours" and "getMinutes"), plus one to each, and then output it to the page (with some nice formatting!).
So something like this:
var current = new Date();
var hours = current.getHours();
var minutes = current.getMinutes();
if(minutes < 10){
minutes = '0' + minutes; //See description below
}
document.write(hours + ':' + minutes + ' ');
if(hours > 11)
{
document.write('pm');
}
else
{
document.write('am');
}
Most of this is pretty self explanatory, but you may be wondering why we prepend a "0" to the minutes when they're under 10. This is simply to prevent behavior such as "10:9" and correct it to "10:09".
It would display something like this on the page:
Back to Javascript

