PHP includes a lot of date and time functions. These functions are coming under PHP date and time-related extensions.
These are used perform various operations with date and time, like getting date time information based on the input or parameters passed, performing date time manipulation, converting date input formats from one another and more.
In this tutorial, we are going to see the basic functions of the PHP date and time-related extension. I am giving few examples for doing the below date and time functionalities.
- Getting the current date and time information.
- Getting the current date in a specified format.
- Calculating timestamp of the given date.
Getting the Current Date and Time Information
The PHP getdate() function is used to get the array of date and time information for the current date. It returns the day of the month, the day of the week, year of the week, the month of the year, month name, hour, minute, second and the timestamp in an array.
The following code shows the usage of this function and the output array it returns.
$date_components = getdate();
Getting the Current Date in a Specified Format
I used PHP date() function to get the current date in a specified format. This function accepts two arguments. The first argument is the format of the date to be returned and the second parameter is the timestamp.
If the second argument is not passed then the date function will return the current date in the specified format. I specified the MM-DD-YYYY format to the date() function below.
$current_date = date('m-d-Y'); // Will print current date in mm-dd-yyyy format echo $current_date;
Calculating timestamp of the given date
The time() function is used to get the current timestamp. Timestamp is nothing but the number of second passed from January 1st, 1970 midnight at GMT.
And then, if we want to get timestamp of a specified date we should use the PHP function mktime(). This function requires the Hour, Minute, Second, Month, Day and Year in the order of (H, I, S, M, D, Y ) as shown in the following example.
// Will return timestamp for current date, time $current_time = time(); // Will return timestamp for 25th April 2013 $timestamp = mktime(25, 35, 10, 4, 25, 2013);
Other Date and Time-Related Functions
PHP supports a lot of date and time-related functionalities by using its built-in functions. In this section, I have listed few of them as below.
- checkdate() – It validates date by accepting date components in the order of (month, day and year).
- strtotime() – Converts the date string into a timestamp.
- date_diff() – Calculates difference between two date objects and returns the array of differences in an object array.
For advanced Date and Time functionalities like timezone conversion and more, we can use PHP DateTime and DateTimezone class functions.