PHP MySQL tutorial

Date and Time Functions in PHP

Date and time functions are two of the most extensively used PHP functions. These functions are used store time of any activity on a website ranging from posting a blog, purchase by a customer and page views in a specific amount of time. PHP contains special functions to perform these tasks. The most basic of the date and time functions is the date function that is used to format date and time in multiple ways depending upon the parameters passed to it. Have a look at the simple example of the date function.

echo "Date in year-month-day:  " . date("Y-m-d") . "
"; echo "Date in " . date("Y.m.d") . "
"; echo "Day of the weak: " . date("l"). "
"; echo "Printing copyright info: ABC © ".date("Y"); ?>

Download the code
Run the code

In the above example the date function is being used for formatting date in different ways. You can see that different string parameters are being passed to the date function. These string parameters are responsible for displaying the date in different formats. For instance, the first format “Y/m/d” prints the date in the format year-month-day. Here Y represents year in four digits, m represent month and its value is between 01-12 while d can be anything between 01-31. The ‘l’ represents the day of the week in letters.

Apart from date, the date function can also be used for formatting time. Also, the PHP engine is smart enough to convert strings to date if string is passed in valid format. These concepts have been explained in the following example.


echo "Yesterday was ".date("Y/m/d h:i:sa", $yester) . "
"; $nmon=strtotime("next Monday"); echo "Next monday is on ".date("Y/m/d h:i:sa", $nmon) . "
"; $twoyears=strtotime("+2 Years"); echo "Date after two years will be ".date("Y/m/d h:i:sa", $twoyears) . "
"; ?>

Download the code
Run the code

In the above example, time has been printed by passing h, i, s and a to date function. The h corresponds to hour in 12 hour format i.e 01-12, i and s stand for minutes and seconds respectively. They range between 00 to 59. Finally a corresponds to post-meridiem or anti-meridiem. The example also shows how you can use strtotime function in order to obtain time in a specified format. This function takes string as input and returns a value which is passed as second parameter to date function to get the desired date.

<<< Form Validation in PHPValidation and Sanitizing Data Via PHP Filters >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .