Date and time function in PHP

Spread the love

Date and time function in PHP


You may require a date and time functionality in almost every application you make. You will learn about a date and time function in PHP here.

As date and time are a very common and essential part of our day to day life, you should know how you can use them in your web application.

In this tutorial, I will explain to you about a date and time function in PHP and how you can use them in your application.


Let’s see the first function in PHP Date Time functions tutorial which is time().

time():

This function gives the current date and time in seconds in integer format.

The format is called as timestamp and that integer timestamp is the number of seconds elapsed from midnight GMT on 1st January 1970.

Example:

<?php
     echo time();
?>

Output: 1471177944


Let’s see the second function in a date and time function in PHP tutorial which is the date().

date():

As you have seen in the above example, the output of time() function i.e. a timestamp is not in human-readable form.

We are not able to understand which time or date this timestamp is representing. To overcome this problem PHP is having another function i.e. date().

We can change timestamp into date and time format  using date function.

date() function accept the format of date or date and time representation as to the first parameter and timestamp as the second parameter. The output of date will return the formatted date.

Example:

<?php
     $current_time_stamp = time();
     $current_date = date('y-m-d', $current_time_stamp);
     $current_date_time = date('y-m-d h:i:s', $current_time_stamp);

     echo "Current timestamp = ".$current_time_stamp;
     echo "<br>Current date = ".$current_date;
     echo "<br>Current date and time = ".$current_date_time;
?>

Output:

Current timestamp = 1471178548
Current date = 16-08-14
Current date and time = 16-08-14 02:42:28

You can pass different time and date formats in date function’s first parameter to output formatted date and time. a date and time function in PHP will be helpful in every web applications built using PHP.


Spread the love

Leave a Comment