![]() |
![]()
|
Basic JavaScript Date and Time FunctionsAs the title implies, this tutorial will show you how to get the date and time from the visitor's computer and print them to the web page. var hour = now.getHours(); var minute = now.getMinutes(); var second = now.getSeconds(); var monthnumber = now.getMonth(); var monthday = now.getDate(); var year = now.getYear(); Notice that the name of the variable containing the date object and a period are followed by the function name. The function extracts the information from the date object and stores it in the variable named on the left of the equal sign. var ap = "AM";
if (hour > 11) { ap = "PM"; }
if (hour > 12) { hour = hour - 12; }
if (hour == 0) { hour = 12; }
If you want the clock time to represent a 24-hour clock instead of an "AM/PM" representation, simply remove those four lines from the function. <script type="text/javascript" language="JavaScript"><!--
var calendarDate = getCalendarDate();
var clockTime = getClockTime();
document.write('Date is ' + calendarDate);
document.write('<br>');
document.write('Time is ' + clockTime);
//--></script>
The Complete Working Example <html>
<head>
<script type="text/javascript" language="JavaScript">
<!-- Copyright 2002 Bontrager Connection, LLC
function getCalendarDate()
{
var months = new Array(13);
months[0] = "January";
months[1] = "February";
months[2] = "March";
months[3] = "April";
months[4] = "May";
months[5] = "June";
months[6] = "July";
months[7] = "August";
months[8] = "September";
months[9] = "October";
months[10] = "November";
months[11] = "December";
var now = new Date();
var monthnumber = now.getMonth();
var monthname = months[monthnumber];
var monthday = now.getDate();
var year = now.getYear();
if(year < 2000) { year = year + 1900; }
var dateString = monthname +
' ' +
monthday +
', ' +
year;
return dateString;
} // function getCalendarDate()
function getClockTime()
{
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var ap = "AM";
if (hour > 11) { ap = "PM"; }
if (hour > 12) { hour = hour - 12; }
if (hour == 0) { hour = 12; }
if (hour < 10) { hour = "0" + hour; }
if (minute < 10) { minute = "0" + minute; }
if (second < 10) { second = "0" + second; }
var timeString = hour +
':' +
minute +
':' +
second +
" " +
ap;
return timeString;
} // function getClockTime()
//-->
</script>
</head>
<body>
<script type="text/javascript" language="JavaScript"><!--
var calendarDate = getCalendarDate();
var clockTime = getClockTime();
document.write('Date is ' + calendarDate);
document.write('<br>');
document.write('Time is ' + clockTime);
//--></script>
</body>
</html>
That's the complete working example. Create a file with the example and load it into your browser. |
|
| © Copyright 2006 TheUSAWebMaster.com All Rights Reserved. |