3.1. Finding the Current Date and Time
Problem
You want to know what the time or date is.
Solution
Use 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
Discussion
The 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( )
Key |
Value |
---|---|
|
Seconds |
|
Minutes |
|
Hours |
|
Day of the month |
|
Day of the week, numeric (Sunday is 0, Saturday is 6) |
|
Month, numeric |
|
Year, numeric |
|
Day of the year, numeric (e.g., 299) |
|
Day of the week, textual, full (e.g., “Friday”) |
|
Month, textual, full (e.g., “January”) |
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 ...
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.