Using Date and Time Functions in PHPThe sections that follow introduce you to the date- and time-related functions specifically in PHP. Try out each listing for yourself, to see how simple and powerful these functions can be. 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. echo time(); // sample output: 1092065201 // this represents August 9th, 2004 at 08:26AM 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, you may think, 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 (60 * 60 * 24, or 86400) to your current figure and you're done. You can convert this new figure into something friendlier, 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 9.3 lists the elements contained in the array returned by geTDate().
Listing 9.4 uses getdate() in line 2 to extract information from a timestamp, employing a foreach statement to print each element (line 3). You can see typical output in Figure 9.5. The geTDate() function returns the date according to the local time zone. Figure 9.5. Using getdate().
Listing 9.4. Acquiring Date Information with geTDate()1: <?php 2: $date_array = getdate(); // no argument passed so today's date will be used 3: foreach ($date_array as $key => $val) { 4: echo "$key = $val<br>"; 5: } 6: ?> 7: <hr> 8: <? 9: echo "Today's date: ".$date_array['mon']."/".$date_array['mday']."/". 10: $date_array['year']."<p>"; 11: ?> 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 9.4 lists some of the codes that a format string can contain. You can find the complete list at http://www.php.net/date. Any other data you include in the format string passed to date() is included in the return value.
Listing 9.5 puts a few of these format codes to the test. Listing 9.5. Formatting a Date with date()1: <?php 2: $time = time(); //stores the exact timestamp to use in this script 3: echo date("m/d/y G.i:s", $time); 4: echo "<br>"; 5: echo "Today is "; 6: echo date("j of F Y, \a\\t g.i a", $time); 7: ?> Listing 9.5 calls date() twice: the first time on line 3 to output an abbreviated date format, and the second time on line 6 for a longer format. Save the text of this listing in a file called datetest.php and open it in your Web browser. Your date will differ from the following, obviously, but here's some sample output: 08/09/04 8.39:16 Today is 9 of August 2004, at 8.39 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. Another example would be in the context of a word you are adding to a string; for example, the. The word the is made up of three format codes, so all must be escaped: <?php echo date("l \\t\h\e jS"); //prints Monday the 15th ?> 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 9.6 uses mktime() to get a timestamp that we then use with the date() function. Listing 9.6. Creating a Timestamp with mktime()1: <?php 2: // make a timestamp for Aug 23 2003 at 4.15 am 3: $ts = mktime(4, 15, 0, 8, 23, 2003); 4: echo date("m/d/y G.i:s", $ts); 5: echo "<br>"; 6: echo "The date is "; 7: echo date("j of F Y, \a\\t g.i a", $ts ); 8: ?> We call mktime() on line 3 and assign the returned timestamp to the $ts variable. We then use the date() function on lines 4 and 7 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 mktimetest.php and open it in your Web browser. You should see 08/09/04 8.53:00 The date is 9 of August 2004, at 8.53 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, as negative numbers are not valid dates. Because the epoch began January 1, 1970, anything before that is an invalid (negative) timestamp. |