Php provides a very enhanced date and time functions. There are a lot of different use cases for date and time functions. We will try to look at most of them in this tutorial.
PHP date() Function
date() function is used to get a date in different formats. date() function can be used to get timestamps too. Unix Timestamp is the second count from January 1, 1970. The syntax of the date function is like below. Here TIMESTAMP is optional so if we want to get the current date we do not need to provide TIMESTAMP.
In this example, we will get the current date as
<?php echo date('d-m-y'); ?>
This will print the following date.
PHP date() Function Formatting
Php provides a rich set of printing options. In this part, we will look at formatting options. Here the list.
drepresents day in 01 and 31 format
Drepresents day in Mon to Sun format
mrepresents the month in 01 to 12 format
Mrepresents month abbreviated Jan to Dec format
yrepresents the year in two digits from 08 to 14 format
Yrepresents the year in four digits 2008 or 2017 format
hrepresents hour in 12-hour format from01 to 12
Hrepresents hour in 24-hour format from 00 to 24
irepresents minutes in two digits 00 to 59
srepresents seconds in two digits 00 to 59
arepresents lowercase ante meridiem and post meridiem am or pm
- A represents lowercase ante meridiem and post meridiem AM or PM
PHP time() Function
Another useful function provided by Php is
time() . The time() function is used to get the current time Unix timestamp. The current timestamp can get like the below example.
<?php echo time(); ?>
This will print an integer value like below.
Convert Timestamp To Date
We can convert the given timestamp into a date format. We will remember that date() function will get time stamp as a second argument. In this example we will give timestamp we get previously and print it more human-readable format.
<?php $timestamp =1496680560; echo date('d-m-y h:i',$timestamp); ?>
We will get the following output.
PHP mktime() Function
Sometimes we need to generate timestamp with a given date and time. This means we do not want to get current time timestamp. In this situation, we can use
mktime() function. Syntax of mktime() function is like below.
mktime( hour , minute , second , month , day , year );
In this example, we will provide the first day of 2017.
<?php echo mktime( 0 , 0 , 0 , 1 , 4 , 2017 ); ?>
This code will generate the following output.