Login |  Register 
Your open source Rocks PHP Library has really made developing PHP easier!
Alan
 

Date and time

Date and time

Once you start making more complex scripts you will soon need to start using date and times. For instance perhaps you want to record when someone registered in the database or show different images depending on the time of year? When using times it is good practice to first set the timezone you are going to use.
date_default_timezone_set("GMT");
Then you can use the date function to get the required date information. The date function outputs a string based on the format of a inputted date string into the function.
echo date("h");
//outputs the current hour as a number from 01-12
echo date("H");
//outputs the Month from Jan to Dec
echo date("d");
//outputs the current hour as a number from 01-23
echo date("D");
//outputs the day from Mon to Sun
echo date("m");
//outputs the current month as a number from 01-12
echo date("M");
//outputs the Month from Jan to Dec
echo date("y");
//outputs the current year as a two digit number
echo date("Y");
//outputs the current year as a four digit number
These string formats can of course be combined to make up more complex numbers. There are also plenty more format options please see the PHP website for more.
echo date("d-m-y");
//outputs the current year so 05-12-2008
So this can be used like so
if (date("m") == 12)
{
 //show christmas logo
}
else
{
 //show normal logo
}
There are two parameters in the date function the first is the string function and the second is the timestamp it should base the date on. Which defaults to the time now, however a future or past timestamp can be used to manipulate a future or past date. Therefore using the time function we shall go back one day. Note the time function outputs the current time stamp.
$timestamp = time();
$timestamp = $timestamp - (24 * 60 * 60);
//minus 24 hours * 60 minutes * 60 seconds
//as the timestamp is minutes since January 1 1970 00:00:00 GMT
echo date("d-m-y", $timestamp);
//outputs the current year so 04-12-2008, when the current date is the 05-12-2008 for instance.

No comments have been provided.
security image
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38