27 Aug 09 PHP Programming Tutorial: Date and Time



Many programmers use dates and times in their scripts. For example, you may want to display a special message to your visitors on the weekends only. PHP has built-in functions with the ability to recognize and work with dates and times (also known as timestamps) taken from the web server.

To begin, let’s try outputting today’s date to the browser.

1. If WampServer is not running, go ahead and start it. Then open your code editor, create a new file called dates.php and save it to your “introduction” directory under c:\wamp\www

2. Type in the code below (with or without the comments — your choice):

<html>
<head>
<title>PHP Dates & Times</title>
</head>
<body>
<?php
// Using PHP's date function to assign today's date to the variable $date
$date = date('Y/m/d');
 
echo $date; // Output the $date to the browser.
?>
</body>
</html>

3. Save the file. In your Web browser, go to: http://localhost/introduction/dates.php

Aha, so we see today’s date formatted as numerical values. It’s like magic. The good kind of magic, not the kind that I try to do to impress my nieces. Anyway, I wrote this article on July 11, 2009, so I see: 2009/07/11

The format for the date function works like this:

$date_variable = date("format_of_date", $timestamp);

The “format_of_date” is a string that instructs PHP on how to store the date in the variable. In our example above, we used the “Y/m/d” string. We could have used another string, like “y.m.d”, which would return: 09.7.11. The $timestamp tells PHP where to find the date information. If no $timestamp is used, like in our above example, then PHP just grabs the current date from the web server.

4. Here are some other examples of dates and times. Experiment with the code yourself in your dates.php file.

<html>
<head>
<title>PHP Dates & Times</title>
</head>
<body>
<?php
// Using PHP's date function to assign today's date to the variable $date
$date = date('Y/m/d');
 
echo $date . "<br />"; // Output the $date to the browser.
echo time() . "<br />"; // Output the current time.
echo date("F j, Y, g:i a") . "<br />"; // July 11, 2009, 5:16 pm
echo date("m.d.y") . "<br />"; // 07.11.09
echo date("j, n, Y") . "<br />"; // 11, 7, 2009
echo date("Ymd") . "<br />"; // 20090711
echo date("D M j G:i:s T Y") . "<br />"; // Sat Jul 11 17:16:18 MST 2009
echo date("H:i:s") . "<br />"; // 17:16:18
?>
</body>
</html>

Refresh your dates.php file in your Web browser to see the results. We’ve shown many different examples of strings that PHP can handle. But what do all these letters in the string mean? For the most up to date reference, check out PHP.net’s Date function page: http://www.php.net/manual/en/function.date.php

Go back to Building PHP Scripts.

Leave a Comment