Displaying Time or Date with PHP
Firstly, make sure that your page file is saved as a .php file it and not .htm, .html, or .asp. Now you page will be able to ‘parse’ PHP code within your document.
<?php echo date("d-m-Y"); ?>
This will results in today’s date appearing as “29-12-2008”. Please note: You will need to upload your page to a server and view it through a browser in order for this to work. PHP is server-side, so unless you have a server set up on your computer, you won’t be able to see the results of this offline.
Okay, we can see the date echoed-out on screen. Now we will look at altering the date format.
<?php echo date("Y-m-d"); ?>
Refresh your browser. The order in which the date appears changes from “29-12-2008” to “2008-12-29”. Very simple.
You may also want to change the way in which the date is display with regards to the length of the year or month number to actual month name.
echo “Today’s date is “.date(“d-m-Y”).” (“.date(“jS F y”).” .”) and the time is “.date(“i:G:s a”);
There are many ways of showing the date and time in PHP. For more examples and things to try, visit http://uk3.php.net/manual/en/function.date.php. It is worth noting; time and date information will not update in ‘real-time’. They will be whatever the time and date is at the moment the browser loads the page. In order to refresh the timestamp, you will need to refresh your browser.
Messing around with the date
You can add to or take time from you date in PHP. For instance, you might want to calculate the date in a week from now, this is a little more complex:
<?php $days = 7; $seconds = $days * 86400; /// Don't change $timestamp = time(); $tm = $timestamp+$seconds; $c_date = date("F j, Y", $timestamp); echo "Today: $c_date <br>"; $f_date = date("F j, Y", $tm); echo "Future date: $f_date <br>"; ?>
Formatting a string date
You may want to reformat a date held in a string. You can use strtotime() to do this:
<?php $mydate = "29-12-2009"; $refined_date = date("jS F Y", strtotime($mydate)); echo $refined_date; ?>
Now the string ‘$mydate’, containing ’29-12-2009′ will echo-out as ’29th December 2008′.