Display the current date with PHP
If you have never written anything in PHP before, this is a good little trick to start with. Many websites display the current date at the top of the page, especially news or article sites.
PHP has a function called date, for an in depth discussion see the offical PHP date manual.
Before you try and use any PHP on your website you should make sure your host supports it. Most reasonable hosts do nowadays, if you have gone for an ultra cheap option they may not.
To find out if PHP is supported either look on your hosts website or create a test file:
Open a HTML editor, or notepad an start a new file. In the file write:
<?
echo "PHP works";
?>
The <? part shows that PHP information is starting, and ?> shows PHP information is ending. The 'echo' is used to display text in the browser, anything within the quotations will be outputted. The ; is required to show the echo has finished.
Then save the file as 'test.php', for PHP to work the file must have the .php extension. Upload the file to your hosting, and open it in your browser. You should see 'PHP works' displayed.
Display the current date
Now you know PHP is working, it's time to display the current date. There are many ways to format the date and time. The PHP manual has explanations of all of these. I suggest you copy and paste the code below into your test page to begin with.
<?
echo date('l jS \of F Y h:i:s A');
?>
This version gives a very full human friendly version of the date, with the day name(l), day of month(j), English ordinal suffix(S), A full textual representation of a month (F), A full numeric representation of a year, 4 digits(Y), hours(h), minutes(i), seconds(s) and finally uppercase Ante meridiem and Post meridiem (A).
If you don't want all of this information you can simply remove some of the letters from the date function.
If you refresh the browser whilst viewing the date and time you will see the time change.
If your hosting is in the same country as you are, and you want to display the local date/time this technique should work fine. If you have hosting in a different country, or want to display the date and time of another country, you may need to use the date_default_timezone_set function, you can also use the INI setting date.timezone to set the default timezone.
Posted by Tom on Fri 14th Aug 2009