O'Reilly logo

PHP Cookbook by Adam Trachtenberg, David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

Seconds

minutes

Minutes

hours

Hours

mday

Day of the month

wday

Day of the week, numeric (Sunday is 0, Saturday is 6)

mon

Month, numeric

year

Year, numeric

yday

Day of the year, numeric (e.g., 299)

weekday

Day of the week, textual, full (e.g., “Friday”)

month

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required