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

Get PHP Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.