Php – Date and Time


Php provides very enhanced date and time functions. There are a lot of different use cases for date and time functions. We will try to look most of them in this tutorial.

Date() Function

date() function is used to get date in different formats. date() function can be used to get timestamp 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 day-month-year format.

This will print the following date.


Php provides a rich set of printing options. In this part, we will look at formatting options. Here the list.

  •  d represents day in 01 and 31 format
  • D represents day in Mon to Sun format
  • m represents the month in 01 to 12 format
  • M represents month abbreviated Jan to Dec format
  • y represents the year in two digits from 08 to 14 format
  • Y represents the year in four digits 2008 or 2017 format
  • h represents hour in 12-hour format from01 to 12
  • H represents hour in 24-hour format from 00 to 24
  • i represents minutes in two digits 00 to 59
  • s represents seconds in two digits 00 to 59
  • a represents lowercase ante meridiem and post meridiem am or pm
  • A represents lowercase ante meridiem and post meridiem AM or PM
LEARN MORE  How To Use vmstat To Monitor Linux Performance

Time Function

Another useful function provided by Php is time() . The time() function is used to get current time Unix timestamp. The current timestamp can get like below example.

This will print an integer value like below.

Convert Timestamp To Date

We can convert given timestamp into date format. We will remember that date() function will get time stamp as second arguments. In this example we will give timestamp we get previously and print it more human-readable format.

We will get the following output.

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.

In this example, we will provide the first day of 2017.

This code will generate the following output.


Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)