Being able to set the value of a input field to have the current date can be useful; but problems can arise - especially if you're using getYear() due to inconsistencies between Microsoft Internet Explorer and Mozilla Firefox. This article describes how to get round these problems.
Dates in JavaScript are handled using the Date class. In the following example we create an instance of this class and use the getYear() and getFullYear() methods to alert the current year.
// Create instance of Date class
var currentDate = new Date();
// IE: alerts "2007"
// Firefox: alerts "107"
alert(currentDate.getYear());
// Both: alert "2007"
alert(currentDate.getFullYear());
In this example it is assumed the year is 2007. These inconsistencies show that if you require the year in full, i.e. 2007, then you should use the getFullYear() function. If you only want a two-digit year than I recommend the following:
// Create instance of Date class
var currentDate = new Date();
var theYear = currentDate.getFullYear().toString().substring(2);
This will instead take the full year, 2007, and then cast it into a String so that string methods can be performed on it. This is followed by substring(2) which will take the string from the 3rd character onwards (position is counted from zero).
We can do more with time too, the following methods are available to us:
- getDay()
- This will provide the day of the week (0 = Sunday ... 6 = Saturday)
- getDate()
- This will provide the day of the month (1 - 31)
- getMonth()
- Returns the month as an integer (0 = January ... 11 = December)
- getYear()
- This is dependant on the browser. In FireFox it will produce a 2-digit year (though since it is counting from 1900, the year in 2000 is 100, 2007 is 107, etc,). Internet Explorer 6 and above see this as a 4 digit date. See above for details.
- getFullYear()
- This will return a 4 digit year in the range of 1970 to 9999.
- getTime()
- This provides the number of milliseconds since the epoch (January 01 1970 00:00:00).
- getSeconds()
- The number of seconds (0 - 59)
- getMinutes()
- The number of minutes (0 - 59)
- getHours()
- The number of hours in 24-hour format (0 - 23)
It can also be useful to pad out the number of zero's so that 1/1/1970 would read as 01/01/1970. the following function can be used to sort this.
function zeroPad (str)
{
while (str.toString().length < 2) {
str = '0' + str;
}
return str;
}
var d = new Date();
zeroPad(d.getDate()) + '-' + zeroPad(d.getMonth() + 1) + '-' + d.getFullYear();
With the above example, if the date was 29/7/2007, it would be reformatted as 29/07/2007.
That is all there is to dates in JavaScript! Simple enough.