3.2. Finding the Current Date and Time3.2.1. ProblemYou want to know what the time or date is. 3.2.2. SolutionUse strftime( ) or date( ) for a formatted time string: print strftime('%c'); print date('r'); Mon Aug 12 18:23:45 2002 Mon, 12 Aug 2002 18:23:45 -0400 Use getdate( ) or localtime( ) if you want time parts: $now_1 = getdate( ); $now_2 = localtime( ); print "$now_1[hours]:$now_1[minutes]:$now_1[seconds]"; print "$now_2[2]:$now_2[1]:$now_2[0]"; 18:23:45 18:23:45 3.2.3. DiscussionThe functions strftime( ) and date( ) can produce a variety of formatted time and date strings. They are discussed in more detail in Recipe 3.5. Both localtime( ) and getdate( ), on the other hand, return arrays whose elements are the different pieces of the specified date and time. The associative array getdate( ) returns has the key/value pairs listed in Table 3-1. Table 3-1. Return array from getdate( )
For example, here's how to use getdate( ) to print out the month, day, and year: $a = getdate( ); printf('%s %d, %d',$a['month'],$a['mday'],$a['year']); August 7, 2002 Pass getdate( ) an epoch timestamp as an argument to make the returned array the appropriate values for local time at that timestamp. For example, the month, day, and year at epoch timestamp 163727100 is: $a = getdate(163727100); printf('%s %d, %d',$a['month'],$a['mday'],$a['year']); March 10, 1975 The function localtime( ) returns an array of time and date parts. It also takes an epoch timestamp as an optional first argument, as well as a boolean as an optional second argument. If that second argument is true, localtime( ) returns an associative array instead of a numerically indexed array. The keys of that array are the same as the members of the tm_struct structure that the C function localtime( ) returns, as shown in Table 3-2. Table 3-2. Return array from localtime( )
For example, here's how to use localtime( ) to print out today's date in month/day/year format: $a = localtime( ); $a[4] += 1; $a[5] += 1900; print "$a[4]/$a[3]/$a[5]"; 8/7/2002 The month is incremented by 1 before printing since localtime( ) starts counting months with 0 for January, but we want to display 1 if the current month is January. Similarly, the year is incremented by 1900 because localtime( ) starts counting years with 0 for 1900. Like getdate( ), localtime( ) accepts an epoch timestamp as an optional first argument to produce time parts for that timestamp: $a = localtime(163727100); $a[4] += 1; $a[5] += 1900; print "$a[4]/$a[3]/$a[5]"; 3/10/1975 3.2.4. See AlsoDocumentation on strftime( ) at http://www.php.net/strftime, date( ) at http://www.php.net/date, getdate( ) at http://www.php.net/getdate, and localtime( ) at http://www.php.net/localtime. Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|