When developing more complex PHP sites, especially forums, discussion boards and blogs where date and time functions are important, you’ll regularly encounter situations where you need to display and manipulate values based around the current date and time. PHP includes a range of functions which can help you to easily format and adjust your date and time displays to suit your needs. In this tutorial, we’ll look at some easy ways to display calendar information for your visitors.
One of the simplest date/time functions in PHP is time(). This simple function takes no arguments, and simply returns a numeric value equal to the number of seconds since the “Unix Epoch”, declared as January 1st 1970 at midnight (GMT) - just an arbitrary date chosen to base timing calculations on when working with dates and times. This gives a start time upon which we can base our time calculations
$time = time(); echo $time; //gives us something like 1219075172
This timestamp can then be used as input to the date() function to format it for improved readability. The date() function takes, as its arguments, a string to define how we wish the formatted time to appear and secondly, a Unix timestamp just like the one returned by time(). It is also possible to use date() without specifying a timestamp and it will use the current time as its source.
echo date("F j, Y, g:i a", 1219075172); //produces "August 18, 2008, 4:59 pm"
The string used in the date() function can contain a number of single letters which are then substituted for their human readable counterparts according to the value of the timestamp. In our case, the following substitutions are made
- F: The full textual representation of the month, August in this case
- j: The day of the month, without leading zeros, e.g. 4, 18, 22
- Y: The full year, e.g. 2008
- g: The current hour, in 12-hour format
- i: The current number of minutes
- a: Either am, or pm, depending on the time
A full list of all the codes, and their textual counterparts can be seen on PHP.net’s date() page here. Extra text can be added to the formatted string as required, but remember to escape any characters which date() will interpret as formatting text.
An alternative to the time() function is mktime(). This function is useful when we wish to use a date/time which is not the current time. mktime() takes as its arguments numerical values representing, in this order - hours, minutes, seconds, months, days, years - and a final value to declare whether daylight savings time is to be taken into account.
$date = mktime(10, 15, 0, 12, 12, 1980); //produces 345464100 echo date("F j, Y, g:i a", $date); //produces "December 12, 1980, 10:15 am"



