The Date Object Constructor and Date Object Methods

Below is an example of dynamically generated numbers representing the day of the week, month of the year, day of the month and current year. All this information can be pulled from JavaScript's built-in Date Object using the Date Object Constructor.

First, a new date object is created using the constructor, while simultaneously assigning a variable name to the object. Then the date object methods, getDay(), getMonth(), getDate() and getYear() are used to pull the date information from the client computer's internal calendar. Remember: JavaScript is a zero based language so the day and month values appear to be behind by one at first glance.

var todaysDate = new Date()
// Create a new Date Object

var theDay = todaysDate.getDay()
// getDay() returns integer of 0-6 which will be stored in the variable theDay

var theMonth = todaysDate.getMonth()
// getMonth() returns integer of 0-11 which will be stored in the variable theMonth

var theDate = todaysDate.getDate()
// getDate() returns day of the month which will be stored in the variable theDate

var theYear = todaysDate.getYear()
// getYear() returns year which will be stored in the variable theYear

if (theYear < 2000) theYear += 1900
// fix for y2k bug (in some browsers) when using getYear() method. if theYear is less than 2000, theYear is equal to itself plus 1900
Date methods used to find time are getHours() (returns 0-23), getMinutes() (returns 0-59) and getSeconds() (returns 0-59).

JavaScript returns numeric values for the above date object methods. Since days of the month and years are expressed using numeric values, the integers returned for getDate() and getYear() need no tweaking. But since no one refers to Sunday as "0", or December as "11" (JavaScript begins counting at zero in these cases), we'll need to change those numeric values to meaningful strings. We could use if/else statements, but there is an easier way.

View the Source

Home | Contact