[ Team LiB ] |
![]() ![]() |
Converting a Timestamp with date()You can use getdate() when you want to work with the elements it outputs. Sometimes, though, you only want to display the date as a string. The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument you must pass to it. In addition to the format string, date() optionally accepts a timestamp. Table 16.2 lists the codes a format string can contain; any other data you include in the format string passed to date() is included in the return value.
Listing 16.2 puts a few format codes to the test. Listing 16.2 Formatting a Date with date()1: <!DOCTYPE html PUBLIC 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.2 Formatting a Date with date()</title> 7: </head> 8: <body> 9: <div> 10: <?php 11: print date("m/d/y G.i:s", time()); 12: // 10/08/03 19.17:42 13: print "<br/>"; 14: print "Today is "; 15: print date("jS of F Y, \a\\t g.i a", time()); 16: // Today is 8th of October 2003, at 7.17 pm 17: ?> 18: </div> 19: </body> 20: </html> In Listing 16.2 we call date() twice—the first time on line 11 to output an abbreviated date format, the second on line 15 for a longer format. Although the format string looks arcane, it is easy to build. If you want to add a string to the format containing letters that are format codes, 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. "\n" should become "\\n", for example, if you want to include an n in the format string. date() returns information according to your local time zone. If you want to format a date in GMT, you should use the gmdate() function, which works in exactly the same way. ![]() |
[ Team LiB ] |
![]() ![]() |