Приглашаем посетить
Чуковский (chukovskiy.lit-info.ru)

12.5 Getting date and time information from server

Table of Contents

Previous Next

12.5 Getting date and time information from server

12.5.1 Why server time?

From the canonical clientserver interaction, we know that a server is basically a machine to hold XHTML (or HTML) files and send them to the browsers. In fact, the capabilities of servers are far beyond the original HTML imagination. Enhanced by various Web technologies including security, they can perform all kinds of processing, manipulations and protection checks before sending the XHTML (or HTML) files. Server technologies will be discussed in Parts IV and V. In the following sections, we will introduce some techniques that can be used to obtain the date and time information from the server. That is, to ask the server to send date and time to the browser as XHTML information. Why do we need server date and time in the first place? Well, the main advantages of using the server are:

  • A server is usually a more reliable machine that is always running and has a live connection to the Internet.

  • Since users or clients cannot change the date and time information of a server, the record is more reliable and can be used as solid proof of any business activities.

In fact, server time is an integral part of almost any commercial transactions and e-businesses on the Internet.

A formal discussion of server technologies is presented in Part IV. Before that two server technologies are introduced here, namely, Active Server Page (ASP) and PHP Hypertext Preprocessor (PHP). ASP was originated by Microsoft Corporation and can be found in Windows 9.x, NT, 2000, and XP server environments. ASP pages in this book will have file extension .asp. PHP is more platform independent and can be found in most UNIX (or LINUX) installations. PHP pages or scripts will have file extension .php. As a user, you need to find out what type of technologies are supported by your server (or ISP). For obvious reasons, only simple server applications involving date and time will be considered here.

In addition to the server date and time, we will also show you how to integrate them with all the techniques that you have learned in previous sections. Now, let's see how to obtain a date and time from a server using ASP.

12.5.2 Server date and time using ASP

Microsoft's ASP provides a framework for using existing scripting languages such as ECMAScript (or JScript) at the server level. An ASP script can perform a task as simple as displaying the value of a variable to one as complex as sending a Structured Query Language (SQL) statement to a complicated database structure shared among big organizations. There are two basic scripting languages used in ASP, VBScript (a small version of Visual Basic) and JScript. Since JScript is a full implementation of ECMA-262 (i.e., ECMAScript), JScript is used for our discussion here.

If your server supports ASP, you can use the following two procedures to convert all your XHTML files to ASP.

  • Rename the XHTML files with extensions .htm, .html, or .xhtml to .asp.

  • Copy and paste the following ASP statement to line 1 of the file:

    
    

    <%@language="JScript" %>
    

For VBScript, users may use <%@language="VBScript" %> instead. Our next example is an ASP conversion of ex12-03.htm. This converted example, ex12-20.asp, is listed as follows:



Example: ex12-20.asp - Date Functions

 1: <%@language="JScript" %>
 2: <?xml version="1.0" encoding="iso-88591"?>
 3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 6: <head><title>Date Functions -- ex1220.asp</title></head>
 7: <body style="background:#000088;text-align:center;font-family:arial;
 8:     font-size:16pt;color:#ffff00">
 9: <script>
10: <% cDate = new Date() %>
11: document.write("Getting Today's Date From The Server<br /><br />")
12: document.write("The Day of The Week = "+ <%= cDate.getDay()%> +"<br />")
13: document.write("The Date of The Month = "+<%= cDate.getDate()%>+"<br />")
14: document.write("The Current Month = "+<%= (cDate.getMonth()+1)%>+"<br />")
15: document.write("The Current Year = "+<%= cDate.getFullYear()%>+"<br />")
16: </script>
17: </body>
18: </html>

Any statements between the ASP bracket pair <% and %> will be processed by the server before sending them back to the browser. As you can see from this example, all ASP date and time functions and commands are the same as ECMAScript. They are bracketed with the ASP element pair. The equal sign (=) used in the bracket pair in line 12



<%= cDate.getDay() %>

means print out the value of cDate.getDay(). That is, get the weekday from the server and output the value at the current location. We have put this page into a system that supports ASP, such as the Internet Information Server (IIS). You can issue the following command on a browser to see the result:

http://www.pwt-ex.com/book/chap12a/ex12-20.asp

If you have the ASP program ex12-20.asp stored in the appropriate folder or location, you will see the result of this page as in Fig. 12.23.

Figure 12.23. ex12-20.htm

graphics/12fig23.jpg


As for curiosity, if you activate the "view source" option from the browser, you will see the source code of this page as in listing ex12-15.txt.



Listing: ex12-15.txt - The XHTML Page Generated By ex1220.asp

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> Date Functions -- ex1220.asp </title></head>
 6: <body style="background:#000088;text-align:center;font-family:arial;
 7:     font-size:16pt;color:#ffff00">
 8: <script>
 9:
10:  document.write("Getting Today's Date From The Server<br /><br />")
11:  document.write("The Day of The Week = "+ 6 +"<br />")
12:  document.write("The Date of The Month = "+20+"<br />")
13:  document.write("The Current Month = "+9+"<br />")
14:  document.write("The Current Year = "+2003+"<br />")
15: </script>
16: </body>
17: </html>

If you compare this page with ex12-20.asp, you can see that the server actually generates the date and time information. These values are then returned to the browser as a formatted XHTML file.

The manipulation of static date and time is easy. All you have to do is enclose the statements inside the ASP element pair <% and %>. For dynamic date and time, however, some special treatment is needed.

12.5.3 Dynamic time implementation with ASP

In order to save the resources of Internet traffic and valuable server time, and for many other practical reasons, a mechanism that keeps calling the server date and time functions is not recommended. Instead a server reference technique may be more appropriate in practice. The idea is simple: for example, you first get the server time as a reference or a starting point. The increment of the local time is then used to update this reference. This way, you have an instant dynamic clock with server time.

Consider the following example ex12-21.asp. This example is a modification of ex12-13.htm to create dynamic server time.



Example: ex12-21.asp - Server Clock

 1: <%@language="JScript" %>
 2: <?xml version="1.0" encoding="iso-88591"?>
 3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 6: <head><title>Server Clock - ex1221.asp</title></head>
 7: <style> .mSt{font-size:16pt;color:#ffff00;font-weight:bold } </style>
 8: <body style="background:#000088;text-align:center;font-family:arial"
 9:             onload="Clock03()">
10: <div class="mSt" style="font-size:20pt;color:#00ffff" align="center">
11:   <br />Some Popular Time Formats<br />For A Clock On Server<br /><br />
12: <table class="mSt" cellspacing="10">
13:   <tr><td>Military Time :</td><td><div id="mTimeL"></div></td></tr>
14:   <tr><td>Digital Time:</td><td><div id="dTimeL"></div></td></tr>
15:   <tr><td>Standard Time:</td><td><div id="sTimeL"></div></td></tr>
16: </table>
17: </div>
18: <script>
19: fdateObj = new Date()
20: <%sDate = new Date()%>
21: sgetTime = <%=sDate.getTime()%>
22: dTime = sgetTime - fdateObj.getTime()
23:
24: function Clock03()
25: {
26:  dateObj = new Date()
27:  sTime = dateObj.getTime() + dTime
28:  dateObj.setTime(sTime)
29:
30:  cHours = dateObj.getHours()
31:  cMinutes = dateObj.getMinutes()
32:  cSeconds = dateObj.getSeconds()
33:
34:  militaryTimeSt= ((cHours < 10)? '0':'')+cHours+':'+
35:  ((cMinutes < 10)? '0':'')+cMinutes
36:
37:  digitalTimeSt= ((cHours < 10)? '0':'')+cHours+':'+
38:   ((cMinutes < 10)? '0':'')+cMinutes+':'+((cSeconds < 10)? '0':'')+
39:   cSeconds
40:
41:  standardTimeSt= ((cHours==0 || cHours==12) ? '12': cHours %12)+':'+
42:  ((cMinutes < 10)? '0':'')+cMinutes+':'+((cSeconds < 10)? '0':'')+
43:  cSeconds+((cHours < 12) ? ' AM':' PM')
44:
45:  document.getElementById("mTimeL").innerHTML=militaryTimeSt
46:  document.getElementById("dTimeL").innerHTML=digitalTimeSt
47:  document.getElementById("sTimeL").innerHTML=standardTimeSt
48:  setTimeout("Clock03()",1000)
49: }
50: </script>
51: </body>
52: </html>

Line 19 declares a local date object and line 20 a date object on the server. The difference in the server time and local time dTime in line 22 is the reference. This reference is then used in line 27 to get the server time string sTime. The setTime() method used in line 28 is to create a date object with the server time string. This date object can then be used by any date and time functions associated with the browser as if it is a local time object. The setTimeout()method (see line 48) fires up the regular update so that the clock is moving. A screen shot of this page is shown in Fig. 12.24.

Figure 12.24. ex12-21.htm

graphics/12fig24.jpg


12.5.4 Countdown with ASP

Another more practical example is the construction of a countdown page to Christmas Day using server time. This page, ex12-22.asp, has the following listing:



Example: ex12-22.asp - Server Countdown With Images

 1: <%@language="JScript" %>
 2: <?xml version="1.0" encoding="iso-88591"?>
 3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 6: <head><title>Server Countdown With Images - ex1222.asp</title></head>
 7: <style> .mSt{font-size:16pt;color:#ffff00;font-weight:bold } </style>
 8: <body style="background:#000088;text-align:center;font-family:arial"
 9:             onload="countXmax()">
10: <div class="mSt" style="color:#00ffff;font-size:20pt" align="center">
11:      <br />Countdown To Next Christmas <br />(Server Time)<br /><br />
12:  <span id="xmaxL" class="mSt"></span><br /><br />
13:  <table class="mSt" width="250" >
14:  <tr><td>Days</td><td><span id="dayL" class="mSt"></span></td></tr>
15:  <tr><td>Hours</td><td><span id="HoursL" class="mSt"></span></td></tr>
16:  <tr><td>Minutes</td><td><span id="MinutesL" class="mSt"></span></td></tr>
17:  <tr><td>Seconds</td><td><span id="SecondsL" class="mSt"></span></td></tr>
18:  </table>
19: </div>
20: <script>
21:  mDay = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday",
22:      "Friday","Saturday")
23:
24: fdateObj = new Date()
25: <%sDate = new Date()%>
26: sgetTime = <%=sDate.getTime()%>
27: dTime = sgetTime - fdateObj.getTime()
28:
29:  xmaxObj = new Date()
30:  xmaxObj.setMonth(11)
31:  xmaxObj.setDate(24)
32:  xmaxObj.setHours(23)
33:  xmaxObj.setMinutes(59)
34:  xmaxObj.setSeconds(59)
35:
36: function countXmax()
37: {
38:
39:  dateObj = new Date()
40:  sTime = dateObj.getTime() + dTime
41:  dateObj.setTime(sTime)
42:
43:  cYear = dateObj.getFullYear()
44:  cHours = dateObj.getHours()
45:  cMinutes = dateObj.getMinutes()
46:  cSeconds = dateObj.getSeconds()
47:  cTimeDiff = (xmaxObj.getTime() - dateObj.getTime())
48:  if (cTimeDiff < 0)
49:  {
50:   xmaxObj.setFullYear(cYear+1)
51:   cTimeDiff = (xmaxObj.getTime() - dateObj.getTime())
52:  }
53:  xmaxSt=mDay[xmaxObj.getDay()+1]+' December '+
54:         ' 25 '+xmaxObj.getFullYear()
55:  cDays = Math.floor(cTimeDiff/(1000*60*60*24))
56:
57:  tmp1 = Math.floor(cDays/100)
58:  tmp = cDays - (tmp1 * 100)
59:  daySt = '<img src="'+tmp1+'dc.gif" + border="0" '+
60:             ' alt="pic" width="15" height="23" />'+
61:          '<img src="'+(Math.floor(tmp/10))+'dc.gif" + border="0" '+
62:             ' alt="pic" width="15" height="23" />'+
63:          '<img src="'+(Math.floor(tmp % 10))+'dc.gif" + border="0" '+
64:             ' alt="pic" width="15" height="23" />'
65:
66:  tmp = 23-cHours
67:  hourSt = '<img src="'+(Math.floor(tmp/10))+'dc.gif" + border="0" '+
68:              ' alt="pic" width="15" height="23" />'+
69:           '<img src="'+(Math.floor(tmp % 10))+'dc.gif" + border="0" '+
70:              ' alt="pic" width="15" height="23" />'
71:
72:  tmp = 59 - cMinutes
73:  minuteSt = '<img src="'+(Math.floor(tmp/10))+'dc.gif" + border="0" '+
74:               ' alt="pic" width="15" height="23" />'+
75:             '<img src="'+(Math.floor(tmp % 10))+'dc.gif" + border="0" '+
76:               ' alt="pic" width="15" height="23" />'
77:
78:  tmp = 60 - cSeconds
79:  secondSt = '<img src="'+(Math.floor(tmp/10))+'dc.gif" + border="0" '+
80:               ' alt="pic" width="15" height="23" />'+
81:             '<img src="'+(Math.floor(tmp % 10))+'dc.gif" + border="0" '+
82:               ' alt="pic" width="15" height="23" />'
83:
84:  document.getElementById("xmaxL").innerHTML=xmaxSt
85:  document.getElementById("dayL").innerHTML= daySt
86:  document.getElementById("HoursL").innerHTML= hourSt
87:  document.getElementById("MinutesL").innerHTML= minuteSt
88:  document.getElementById("SecondsL").innerHTML= secondSt
89:  setTimeout("countXmax()",1000)
90: }
91: </script>
92: </body>
93: </html>

It is not difficult to see that we have used the same reference technique here. Lines 2427 are used to get the time reference of the server and the local client. This time difference variable (dTime) is used to create the date object with the server time string in lines 4041. The remaining operations are the same as those in ex12-16.htm. The client-side increment of the time in line 89 has an updating effect on the server time.

Once you understand this idea, you can tackle a slightly different server technology, namely PHP Hypertext Preprocessor (PHP).

12.5.5 Server date and time using PHP

PHP is similar to ASP in that they are both server-side scripting languages. In principle, they both process a file and produce an XHTML file for the browser. The commands and how to use them, of course, are different. PHP is considered as another popular server technology on the Web based on the following two reasons:

  • PHP is simple to use yet powerful enough to handle complicated problems such as databases in a surprisingly simple way.

  • PHP is freely available on most platforms (from Microsoft Windows to LINUX systems).

As an introduction (and a good starting point), only PHP's date and time applications are considered here. A more formal discussion of PHP follows in Part IV.

To handle date and time information using PHP, you need to remember the following five points:

  • PHP files should have the file extension .php.

  • PHP statements (or commands) should be enclosed by the PHP pair <?PHP and ?>.

  • PHP variables have prefix $ (such as $myVar).

  • PHP uses echo as output statements such as echo("My Message").

  • PHP statements terminate with a semi-colon such as echo("My Message");.

With these in mind, let's consider the following example ex12-23.php:



Example: ex12-23.php - Getting Date & Time Using PHP

 1: <?PHP echo"<?";?>xml version="1.0" encoding="iso-88591"<?PHP echo"?>";?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> Example: ex1223.php </title></head>
 6: <body style="background:#000088;text-align:center;font-family:arial;
 7:     font-size:16pt;color:#ffff00">
 8: <?PHP
 9:  $today = getdate();
10:    $month = $today['month'];
11:    $mday = $today['mday'];
12:    $year = $today['year'];
13:    $hours = $today['hours'];
14:    $minutes = $today['minutes'];
15:    $seconds = $today['seconds'];
16:    $weekday = $today['weekday'];
17: ?>
18: <script>
19:  document.write("<br />Getting Today's Date Using PHP<br /><br />")
20:  document.write("The Day of The Week = <?PHP echo "$weekday"; ?> <br />")
21:  document.write("The Date of The Month = <?PHP echo "$mday"; ?> <br />")
22:  document.write("The Current Month = <?PHP echo "$month"; ?> <br />")
23:  document.write("The Current Year = <?PHP echo "$year"; ?> <br />")
24: </script>
25: </body>
26: </html>

As we mentioned earlier, PHP is a preprocessor with the starting element <? and ending with ?>. In fact, the PHP statement



<?PHP echo "<?"; ?>

is used in line 1 to produce the necessary symbol <? for consistent XML coding. Likewise, we also need another one at the end of line 1.

The main PHP date and time block starts from line 8. The getDate() in line 9 is a PHP function used to return an array containing the date and time information. This array is assigned to variable $today. Therefore, $today['month'] contains the information of the current month (see line 10). A series of variables are used to remember the date and time returned by the getDay() function (see lines 1016). If you want to output the value of a variable such as $weekday, you can use the echo statement



<?PHP echo "$weekday"; ?>

as demonstrated in line 20. Since PHP is a preprocessor, the interpretation of the echo command is done before any ECMAScript statement from the browser. Thus you need to include the entire PHP output statement inside the double quotes of the ECMAScript (see line 20). If you put this PHP page into a system with PHP support, such as the UNIX/LINUX environment running Apache, you can use the following "http" command

http://www.pwt-ex.com/book/chap12a/ex12-23.php

to access the page and see the result. A screen shot of the page is shown in Fig. 12.25.

Figure 12.25. ex12-23.php

graphics/12fig25.jpg


Again, if you activate the "view source" option from the browser, you will see the following XHTML coding:



Listing: ex12-15.txt - The Date And Time Page Generated By ex1223.php

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> Example: ex1223.php </title></head>
 6: <body style="background:#000088;text-align:center;font-family:arial;
 7:     font-size:16pt;color:#ffff00">
 8:
 9: <script>
10:  document.write("<br />Getting Today's Date Using PHP<br /><br />")
11:  document.write("The Day of The Week = Saturday <br />")
12:  document.write("The Date of The Month = 20 <br />")
13:  document.write("The Current Month = September <br />")
14:  document.write("The Current Year = 2003 <br />")
15: </script>
16: </body>
17: </html>

12.5.6 A digital clock using PHP

As another application using PHP, let's modify the digital clock in ex12-14.htm to deal with server time. The main page of this example is listed in ex12-24.php.



Example: ex12-24.php - A Digital Clock With Images Using PHP

 1: <?PHP echo"<?";?>xml version="1.0" encoding="iso-88591"<?PHP echo"?>";?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> Example: ex1224.php </title></head>
 6: <style> .mSt{font-size:16pt;color:#ffff00;font-weight:bold } </style>
 7: <script src="date.js"></script>
 8: <script src="imgclock.js"></script>
 9: <body style="background:#000088;text-align:center;font-family:arial">
10: <div align="center"><br />
11:   <div id="myHeader"></div><br /><br />
12:   <div class="mSt">
13:      A Digital Clock With Images<br />(Using PHP)<br /><br /></div>
14:   <div id="clockL"></div>
15: </div>
16:  <script>
17:   fdateObj = new Date()
18:   <?PHP $uTime = mktime(); ?>
19:   sgetTime = <?PHP echo("$uTime \n"); ?>
20:   sgetTime = sgetTime * 1000
21:   dTime = sgetTime - fdateObj.getTime()
22:
23:   document.getElementById("myHeader").innerHTML=disHeader()
24:   document.getElementById("clockL").innerHTML=showClock()
25:   showTime()
26:  </script>
27: </body>
28: </html>

In this page, the same reference technique mentioned in the previous section is used to obtain the dynamic server time. The PHP time function mktime()in line 18



<?PHP $uTime = mktime(); ?>

returns the total number of seconds since January 1, 1970 (the UNIX time convention). A negative value indicates a date before the starting date. This number is assigned to a PHP variable $uTime. The echo statement in line 19 is to output the total seconds so that the ECMAScript variable sgetTime can have this value. Since ECMAScript time is in milliseconds, you need to multiply sgetTime by 1,000 to get the seconds as illustrated in line 20. Once you have done that, the reference time variable dTime will be calculated in line 21. The dTime variable is used as an adjustment to reflect the information of the server time. Since this variable is in the program file imgclock.js, no further modification of imgclock.js is needed. A screen shot of this example is shown in Fig. 12.26.

Figure 12.26. ex12-24.php

graphics/12fig26.jpg


    Table of Contents

    Previous Next