| JavaScript Date and Time The Date object |
Format #3: date-month name-year (something like, 21-March-2001)
The getMonth() function gives us the month in a numeric form. To convert this value into the month name, we will employ an array. The array would contain all the 12 month names.
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + m_names[curr_month]
+ "-" + curr_year);
/* The last two lines above have
to placed on a single line */
//-->
</SCRIPT>
Note: For the sake of clarity, I've written the JavaScript code for the array in multiple lines. For usage, you would have to put this on a single line.
This time, we use the new operator with the Array() constructor and store the 12 month names in the array. Variable m_names stores the array of month names. The value returned by getMonth() is the index at which the month name is stored in the array. Indexes in JavaScript arrays begin at 0; this suits our purpose and we do not need to increment the getMonth() value.
The code above prints: 17-October-2006
Format #4: Like 21st March 2001
In this format we include a superscript to the date value. The idea is to identify the date and then select a superscript based on the date value.
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var d = new Date();
var curr_date = d.getDate();
var sup = "";
if (curr_date == 1 || curr_date == 21 || curr_date ==31)
{
sup = "st";
}
else if (curr_date == 2 || curr_date == 22)
{
sup = "nd";
}
else if (curr_date == 3 || curr_date == 23)
{
sup = "rd";
}
else
{
sup = "th";
}
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "<SUP>" + sup + "</SUP> "
+ m_names[curr_month] + " " + curr_year);
//-->
</SCRIPT>
|
| Return to Listing |