| Getting current time using JavaScript |
Format #5: day date month name year (something like, Wednesday 21st March 2001)
The getDay() method returns a number that specifies the day of the week. Sunday is represented by 0, Monday by 1 and so on. Here again we employ an array. This array would contain the Day names.
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
var d_names = new Array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var d = new Date();
var curr_day = d.getDay();
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(d_names[curr_day] + " " + curr_date + "<SUP>"
+ sup + "</SUP> " + m_names[curr_month] + " " + curr_year);
//-->
</SCRIPT>
Note: For the sake of clarity, I've written the code for the arrays and the write() statement have been written on multiple lines. For usage, you would have to put this on a single line.
The Day name is accessed from the array using the value returned by getDay() as index.
The code above prints: :Tuesday 17th October 2006
Format #6: Hours:Minutes (Finding the time)
Hours and minutes are obtained using getHours() and getMinutes() methods of the date object. The value returned by gethours() varies from 0 to 23.
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
document.write(curr_hour + " : " + curr_min);
//-->
</SCRIPT>
|
| Return to Listing |