Using Date and Time Functions in PHP

The several sections that follow introduce you to the date- and time-related functions specifically in PHP. You learn about the MySQL functions later in this hour. Try each listing yourself, as you march along through this hour.

Getting the Date with time()

PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments and returns an integer. For us humans, the returned number is a little hard on the eyes, but it's extremely useful nonetheless.

 print time(); // sample output: 1127732399 

The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the Unix epoch, and the number of seconds that have elapsed since then is referred to as a timestamp. PHP offers excellent tools to convert a timestamp into a form that humans are comfortable with. Even so, isn't a timestamp a needlessly convoluted way of storing a date? In fact, the opposite is true. From just one number, you can extract enormous amounts of information. Even better, a timestamp can make date arithmetic much easier than you might imagine.

Think of a homegrown date system in which you record days of the month as well as months and years. Now imagine a script that must add one day to a given date. If this date happened to be 31 December 1999, rather than adding 1 to the date, you'd have to write code to set the day of the month to 1, the month to January, and the year to 2000. Using a timestamp, you need only add a day's worth of seconds to your current figure and you're done. You can convert this new figure into something more friendly at your leisure.

Converting a Timestamp with getdate()

Now that you have a timestamp to work with, you must convert it before you present it to the user. getdate() optionally accepts a timestamp and returns an associative array containing information about the date. If you omit the timestamp, getdate() works with the current timestamp as returned by time(). Table 11.1 lists the elements contained in the array returned by getdate().

Table 11.1. The Associative Array Returned by getdate()

Key

Description

Example

seconds

Seconds past the minute (0 59)

28

minutes

Minutes past the hour (0 59)

7

hours

Hours of the day (0 23)

12

mday

Day of the month (1 31)

20

wday

Day of the week (0 6)

4

mon

Month of the year (1 12)

1

year

Year (4 digits)

2000

yday

Day of year (0 365)

19

weekday

Day of the week (name)

Thursday

month

Month of the year (name)

January

0

Timestamp

948370048

Listing 11.1 uses getdate() (line 7) to extract information from a timestamp, employing a foreach statement to print each element (line 8). You can see typical output in Figure 11.1. getdate() returns the date according to the local time zone.

Figure 11.1. Using getdate().

graphics/11fig01.gif

Listing 11.1 Acquiring Date Information with getdate()
   1: <html>   2: <head>   3: <title>Listing 11.1 Acquiring date information with getdate()</title>   4: </head>   5: <body>   6: <?php   7: $date_array = getdate(); // no argument passed so today's date will be used   8: foreach ($date_array as $key => $val) {   9:     print "$key = $val<br>";  10: }  11: ?>  12: <hr>  13: <?  14: print "Today's date: ".$date_array['mday']."/".$date_array['mon']."/".  15:     $date_array['year']."<p>";  16: ?>  17: </body>  18: </html> 

Converting a Timestamp with date()

You can use getdate() when you want to work with the elements that it outputs. Sometimes, though, you want to display the date as a string. The date() function returns a formatted string that represents a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it. In addition to the format string, date() optionally accepts a timestamp. Table 11.2 lists the codes that a format string can contain. Any other data you include in the format string passed to date() is included in the return value.

Table 11.2. Format Codes for Use with date()

Format

Description

Example

a

am or pm (lowercase)

pm

A

AM or PM (uppercase)

PM

d

Day of month (number with leading zeroes)

20

D

Day of week (three letters)

Thu

F

Month name

January

h

Hour (12-hour format leading zeroes)

12

H

Hour (24-hour format leading zeroes)

12

g

Hour (12-hour format no leading zeroes)

12

G

Hour (24-hour format no leading zeroes)

12

i

Minutes

47

j

Day of the month (no leading zeroes)

20

l

Day of the week (name)

Thursday

L

Leap year (1 for yes, 0 for no)

1

m

Month of year (number leading zeroes)

01

M

Month of year (three letters)

Jan

n

Month of year (number no leading zeroes)

1

s

Seconds of hour

24

r

Full date standardized to RFC 822 (http://www.faqs.org/rfcs/rfc822.html)

Wed, 26 Sep 2001 15:15:14 +0100

U

Timestamp

948372444

y

Year (two digits)

00

Y

Year (four digits)

2000

z

Day of year (0 365)

19

Z

Offset in seconds from GMT

0

Listing 11.2 puts a few of these format codes to the test.

Listing 11.2 Formatting a Date with date()
   1: <html>   2: <head>   3: <title>Listing 11.2 Formatting a date with date()</title>   4: </head>   5: <body>   6: <?php   7: $time = time();   8: print date("m/d/y G.i:s", $time);   9: print "<br>";  10: print "Today is ";  11: print date("j of F Y, \a\\t g.i a", $time);  12: ?>  13: </body>  14: </html> 

Listing 11.2 calls date() twice: the first time on line 8 to output an abbreviated date format, and the second time on line 11 for a longer format. Save the text of this listing in a file called listing11.2.php and open it in your Web browser. Your date will differ from the following, obviously, but here's some sample output:

 09/16/02 8.52:06 Today is 16 of September 2002, at 8.52 am 

Although the format string looks arcane, it's easy to build. If you want to add a string that contains letters that are also format codes to the format, you can escape them by placing a backslash (\) in front of them. For characters that become control characters when escaped, you must escape the backslash that precedes them. For example, \t is a format code for a tab, so to ensure that the tab prints, use \\t as in the previous example.

Also note that the date() function returns information according to your local time zone. If you want to format a date in GMT, you use the gmdate() function, which works in exactly the same way.

Creating Timestamps with mktime()

You can already get information about the current time, but you cannot yet work with arbitrary dates. mktime() returns a timestamp that you can then use with date() or getdate(). mktime() accepts up to six integer arguments in the following order:

Hour

Minute

Second

Month

Day of month

Year

Listing 11.3 uses mktime() to get a timestamp that we then use with the date() function.

Listing 11.3 Creating a Timestamp with mktime()
   1: <html>   2: <head>   3: <title>Listing 11.3 Creating a timestamp with mktime()</title>   4: </head>   5: <body>   6: <?php   7: // make a timestamp for Aug 23 2002 at 4.15 am   8: $ts = mktime(4, 15, 0, 8, 23, 2002);   9: print date("m/d/y G.i:s<br>", $ts);  10: print "<br>";  11: print "The date is ";  12: print date("j of F Y, \a\\t g.i a", $ts);  13: ?>  14: </body>  15: </html> 

We call mktime() on line 8 and assign the returned timestamp to the $ts variable. We then use date() on lines 9 and 12 to output formatted versions of the date using $ts. You can choose to omit some or all the arguments to mktime(), and the value appropriate to the current time is used instead. mktime() also adjusts for values that go beyond the relevant range, so an hour argument of 25 translates to 1:00 a.m. on the day after that specified in the month, day, and year arguments.

Save the text of this listing in a file called listing11.2.php and open it in your Web browser. You should see:

 08/23/02 4.15:00 The date is 23 of August 2002, at 4.15 am 

Testing a Date with checkdate()

You might need to accept date information from user input. Before you work with a user-entered date or store it in a database, you should check that the date is valid. checkdate() accepts three integers: month, day, and year. checkdate() returns true if the month is between 1 and 12, the day is acceptable for the given month and year (accounting for leap years), and the year is between 0 and 32767. Be careful, though: A date might be valid but not acceptable to other date functions. For example, the following line returns true:

 checkdate(4, 4, 1066) 

If you were to attempt to build a date with mktime() using these values, you'd end up with a timestamp of -1. As a rule of thumb, don't use mktime() with years before 1902, and be cautious of using date functions with any date before 1970. You learn more about using checkdate() in Hour 12, "Creating a Simple Calendar."



Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
ISBN: 067232489X
EAN: 2147483647
Year: 2005
Pages: 263

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net