PHP includes a lot of date and time functions. These functions are coming under PHP date and time-related extensions.
These are used to 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 a few examples for doing the below date and time functionalities.
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.
<?php $date_components = getdate(); /* * Array * ( * [seconds] => 23 * [minutes] => 22 * [hours] => 8 * [mday] => 29 * [wday] => 1 * [mon] => 5 * [year] => 2017 * [yday] => 148 * [weekday] => Monday * [month] => May *  => 1496038943 * ) */ ?>
I used the 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.
<?php $current_date = date('m-d-Y'); // Will print current date in mm-dd-yyyy format echo $current_date; ?>
The time() function is used to get the current timestamp. The timestamp is nothing but the number of seconds passed from January 1st, 1970 midnight at GMT.
And then, if we want to get the 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.
<?php // 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); ?>
PHP supports a lot of date and time-related functionalities by using its built-in functions. In this section, I have listed a few of them below.
For advanced Date and Time functionalities like timezone conversion and more, we can use PHP DateTime and DateTimezone class functions.
Comments to “Dates and Time in PHP”
hi vincy, how can i create year 1900 to 2014 dropdown by using loop? please help this