Adding today’s date & time to a web page

This is a question that is asked a lot by my students. “How do you add today’s date and timeto a web page? I don’t want to have to manually update it myself!!“.

Well, the answer is with, of course, PHP and it couldn’t be easier.

date() function

In PHP there are over 7000 built-in functions – in simple terms, a little ‘routine’ that can convert, output, ‘do something’, etc to data. The date() function allows you to display the current ‘timestamp’.

Example of date()

<?php
echo date(“d-m-Y”);
?>

As long as you save your page as whatever.php, testing it out in a browser should output (for example) 02-10-2009.

Very simple – but there are plenty of other things you can do with date(). Try this:

<?php
echo date(“H:i:s a”);
?>

Output: 11:47:50 am.

…or this:

<?php
echo date(“l jS F Y”);
?>

Output: Friday 2nd October 2009.

Good stuff, eh? Not too intuitive though, so how are you going to remember these sequence of letters? Visit: http://uk3.php.net/manual/en/function.date.php for a full list.

It is worth pointing out: PHP is a server-side language. The date/time is created as the page is outputting or ‘parsed’ to the browser. It will not update unless you refresh your browser.