Php date() and time() Functions Tutorial – POFTUT

Php date() and time() Functions Tutorial


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.

date(FORMAT,TIMESTAMP);

In this example, we will get the current date as day-month-year format.

<?php 
 
  echo date('d-m-y'); 
 
?>

This will print the following date.

05-05-2017

PHP date() Function Formatting

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

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.

1496680560

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.

05-06-17 07:36

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.

1483477200

LEARN MORE  Python Timestamp Examples with Time Module

Leave a Comment