Getting current time using JavaScript
Sponsored Links
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 type="text/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.
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 type="text/javascript"> <!-- var d = new Date(); var curr_hour = d.getHours(); var curr_min = d.getMinutes(); document.write(curr_hour + " : " + curr_min); //--> </script>
There are two problem here. Firstly, if the hour or minutes is in single digits, JavaScript does not add any leading zeroes. Hence, 05:03 (AM) is printed as 5:3. Secondly, 12:00 AM becomes 0:00 (!). Let's see how to format time correctly.
Page contents: Details on getting the current time on client system (The visitor computer) and formatting and displaying it on a web page.
Comments, questions, feedback... whatever!
Recent Articles
Recent Blog Posts
Popular Articles
- Hotmail Sign In page
- Create a Hotmail account - Instructions
- Create Gmail address
- Download and install Outlook Express
- Get your free Gmail address
- Outlook Express new version
- Create my own email address
- Browers for Windows list
- Get email address
- Color combinations for web sites and pages
- Create Yahoo ID
More web tips & tricks
- Outlook Express Help - tips & tricks (53)
- Windows Live Mail help and tips (36)
- Windows Mail help (25)
- Hotmail help and tips (42)
- Yahoo help & support (45)
- AOL email help (26)
- Gmail help and tips (36)
- Internet tips & tricks (12)
- Web Design tips & tricks (33)
- HTML, Javascript tips tricks (68)
- Web Promotion tips & tricks (8)
- Graphics tips & tricks (20)
