[ Team LiB ] Previous Section Next Section

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 you can then use with date() or getdate(). mktime() accepts up to six integer arguments in the following order:





day of month


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

Listing 16.3 Creating a Timestamp with mktime()
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 16.3 Creating a Timestamp with mktime()</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: // make a timestamp for 1/5/04 at 2.30 am
12: $ts = mktime( 2, 30, 0, 5, 1, 2004 );
13: print date("m/d/y G.i:s", $ts);
14: // 05/01/04 2.30:00
15: print "<br/>";
16: print "The date is ";
17: print date("jS of F Y, \a\\t g.i a", $ts );
18: // The date is 1st of May 2004, at 2.30 am
19: ?>
20: </div>
21: </body>
22: </html>

We call mktime() on line 12, assigning the returned timestamp to the $ts variable. We can then use date() on lines 13 and 17 to output formatted versions of the date using $ts. You can choose to omit some or all of the arguments to mktime(), and the value appropriate to the current time will be used instead. mktime() also adjusts for values that go beyond the relevant range, so an hour argument of 25 translates to 1.00am on the day after that specified in the month, day, and year arguments.

Testing a Date with checkdate()

You might need to accept date information from user input. Before you work with this 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, because 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 would end up with a timestamp of -1. As a rule of thumb, do not use mktime() with years before 1902 and be cautious of using date functions with any date before 1970.

    [ Team LiB ] Previous Section Next Section