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 -0400Use 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, 2002Pass getdate( ) an epoch timestamp as an argument to make the returned array the appropriate ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access