Introduction to PHP Date And Time Function

Introduction to PHP Date and Time

Date and time are the most important factors for planning and scheduling everyday tasks, keeping records, and tracking activity. For any development project, whether it’s a web developing project or even an entire software, you will need to use the date and time functions in one or another way to make the project work. Different programming languages provide you with different approaches to deal with the date and time of your program. These functions can provide you the flexibility to work with time and date by using operations. They include the conversion corresponding to various time zones across the world, performing arithmetic operations on date-time, or even storing and displaying the date and time information. 

PHP provides you two functions: date() and time() that allow you to store, perform various operations and manipulate the formats of the date and time as per the needs of your program specifications.  These functions in PHP provide a wide range of formatted strings in which the date and time can be displayed. You can use the default time zone for the timestamp or can use your own timestamp to display the date. All the default values are by default with respect to the server that is executing your PHP script.

In this article, we will discuss how to use the date and time functions in PHP along with their syntax, formatting options, and hands-on examples for various use-case scenarios. So without any further ado, let’s get started.

What is the PHP Date Function?

The timestamp is a format in which the current date and time of a specific region can be represented. The timestamp format has two sections. The first section contains the current date and the other section contains the current time. Its format goes this way: ‘YYYY-MM-DD hh:mm:ss’. However, this format is hard and inconvenient to read.

To avoid this, PHP provides the date() function that helps to convert timestamps in a readable format. This is an in-built PHP function and makes it easy to work with dates. PHP date() function accepts two arguments and returns an array containing integers. The two parameters that are passed in the PHP date() function are:

  • Format: The format parameter that is passed to date() function is a string that contains different characters, including uppercase and lowercase alphabets, to get a readable date-time format. The first section of the formatted string represents the format for the date, while the other section of the string represents the format for time.

  • Timestamp: Timestamp will provide the information about the date and time whose format you want to change.  However, the timestamp is an optional parameter. If you do not mention timestamp, the date() function will automatically consider the default current date and time for the formatting.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Why Do You Need a PHP Date Function?

UNIX Timestamp is a format for the date and time that the computer reads and stores. UNIX Timestamp gives the date and time as the measure of the seconds that have passed since the starting of the UNIX epoch. UNIX epoch is the total count of seconds that have passed since January 1, 1970 (midnight UTC/Greenwich Mean Time).  While calculating the UNIX epoch, we exclude the total count of leap seconds (in ISO 8601:1970-01-01T00:00:00Z).

However, there are a lot of problems with this type of format for date and time. The very first thing is that most of the systems store these UNIX epoch dates as 32-bit signed integers. This can cause a problem on the date 19th of January, 2038. This problem also goes by the name, the year 2038 problem. Another problem associated with this format is that it is very hard and inconvenient for humans to read the date and time in this manner. To avoid and overcome all these problems, it is common to use the PHP date function to convert this UNIX Timestamp into a more convenient and readable format.

PHP Date Function Syntax

The date() function in PHP converts and returns the formatted time and date concerning the clock that is pre-built into the server which is executing the PHP script. Many websites use the PHP script having the date() function to set their copyright duration to get updated automatically.

Syntax of the date() in PHP:

// Syntax of date() function in PHP

<?php

   date(format,[timestamp]);

?>

Syntax and parameters description:

  • Format: This parameter specifies the format of the date and time that needs to be returned.

  • Timestamp: This parameter can be used to set the timestamp for the date and time that needs to be returned. This is an optional parameter and by default has the current web server’s date and time as the timestamp.

Syntax to get the current timestamp which is by default the timestamp according to the default timezone of your server:

// the time() returns the 

// default timestamp as per the 

// default time zone

time();

The following example will illustrate the date() without specifying the timestamp parameter in PHP. 

<?php

   // store the date returned by

   // the date function in

   // a variable.

   // here timestamp parameter is not

   // provided. So by default, the

   // server's default timestamp will be used.

   $currentDate = date("d/m/Y");       

   // print the date.

   echo "This is the date today in my time zone: ";

    // today's date is stored in the 

   // variable currentDate. 

   echo $currentDate;

?>

PHPDate_1

The following example will illustrate the date() with a specified timestamp parameter in PHP.

<?php

   // store the timestamp returned by

   // the time() function in

   // a variable.

   $timestamp = time();

   // It will be numeric value

   // representing the number of seconds

   // between the Greenwich Mean Time and

   // the current server's time. 

    // this will print the timestamp

   echo 'The default timestamp in seconds is: '. $timestamp;    echo '\n';

   // date function with specifying the

   // above timestamp.

   echo(date("h:i:s A, F d, Y", $timestamp));

?> 

PHPDate_2

Formatting Options Available In the PHP Date and Time Functions

Formatting options available for displaying the date in the PHP date function are:

CHARACTER

DESCRIPTION

d

The d is for displaying the day of the month. Its format goes as two digits with leading zeros and ranges from 01 to 31.

D

The D is for displaying the day of the week. It shows the days in abbreviated form and ranges from Mon to Sun.

m

The m is for displaying the month in numbers. Its format goes as two digits with leading zeros and ranges from 01 to 12.

M

The M is for displaying the month in text. It shows the month in abbreviated form and ranges from Jan to Dec.

y

The Y is for displaying the year in two digits. Its format goes as two digits like 08 for 2008 and 21 for 2021.

Y

The Y is for displaying the year in four digits. Its format goes as four digits like 2008 or 2021.

j

Day number without any leading zeros. (Example - 1 or 31)

l

Complete representation (textual) of day.

w

A day’s numerical representation. (0 for Sunday)

z

The respective day of the year. It varies from 0 to 365.

n

It gives a numeric number for the month.

t

It returns the total number of days in a given month.

L

It suggests whether it's a leap year or not.

a

AM or PM in lowercase.

A

AM or PM in uppercase.

g

An hour’s 12 hour format.

G

An hour’s 24 hour format.

i

Minutes having leading zeros.

O

Greenwich time difference in hours.

T

Abbreviation of the timezone.

o

ISO-8601 number of years.

U

Number of seconds passed since Unix Epoch.

NOTE: You can use special characters between every character like a slash (/), hyphen (-), or a dot (.) to make the format more clean and readable.

Formatting options available for displaying the time in the time function are: 

CHARACTER

DESCRIPTION

h

The h is for displaying the hour in a 12-hour format. Its format goes as two digits with leading zeros and ranges from 01 to 12.

H

The H is for displaying the hour in a 24-hour format. Its format goes as two digits with leading zeros and ranges from 00 to 23.

i

The i is for displaying minutes. Its format goes as two digits with leading zeros and ranges from 00 to 59. 

s

The s is for displaying seconds. Its format goes as two digits with leading zeros and ranges from 00 to 59.

a

The a is for displaying lowercase antemeridian and post meridian (am or pm).

A

The A is for displaying uppercase antemeridian and post meridian (am or pm).

The following example will illustrate the date formatting in different available options in PHP.

 <?php

   // d, D, m, M, y, Y are the available

   // formats for the date() function in PHP.  

   echo "Following are some of the different"

            . "formats to represent today's date.\n";

   echo date("d/m/y");

   echo PHP_EOL;

   echo date("d/m/Y");

   echo PHP_EOL;

   echo date("d-m-y");

   echo PHP_EOL; 

   echo date("d-m-Y");

   echo PHP_EOL; 

   echo date("d.m.y");

   echo PHP_EOL;

   echo date("d.m.Y");

   echo PHP_EOL;

   echo date("D, d M, Y");

   echo PHP_EOL;

?>

PHPDate_3.

What Is the PHP Time Function?

PHP has the time() function that is a built-in function that provides you with the timestamp of the current time. It is a by default functionality of the time() function. This means that you do not have to pass the time to this function. It automatically considers the current time and converts it into the timestamp. As you have already read in the above sections, a timestamp is a value that is in numeric form and is represented by the number of seconds between 1 January 1970 00:00:00 GMT and the current time in your web server. 

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

The time() function does not accept any arguments and unlike the date() function which returns an array of integers, the time() function simply returns an integer that contains the number of seconds. The timestamp thus provided by the time() function can be used in the date function to provide the current date and time. 

The syntax for the time() function is:

// syntax to get the timestamp by using the

// time() in a

// numeric form

// representing the total seconds.

time()

Syntax and parameters description:

The time() in PHP does not require any parameter, and simply returns the total number of seconds between the current time and the UNIX Epoch. 

The following example will illustrate the date formatting in different available options in PHP:

<?php

    // store the current timestamp in a variable.

    // the timestamp returned here by the

    // time() will be in

    // numeric form

    // representing the total seconds.

    $currentTimestamp = time();

    // print the timestamp

    echo 'The current time as a timestamp is: ';

    echo $currentTimestamp;

    echo PHP_EOL;

?>

PHPDate_4

Formatting Options Available In the PHP Time Function

The formatting options available in the PHP time function are:

CHARACTER

DESCRIPTION

h

The h is for displaying the hour in a 12-hour format. Its format goes as two digits with leading zeros and ranges from 01 to 12.

H

The H is for displaying the hour in a 24-hour format. Its format goes as two digits with leading zeros and ranges from 00 to 23.

i

The i is for displaying minutes. Its format goes as two digits with leading zeros and ranges from 00 to 59. 

s

The s is for displaying seconds. Its format goes as two digits with leading zeros and ranges from 00 to 59.

a

The a is for displaying lowercase antemeridian and post meridian (am or pm).

A

The A is for displaying uppercase antemeridian and post meridian (am or pm).

The following example will illustrate the time formatting in different available options in PHP.

<?php 

   //h, H, i, s, a, A are the available

   // formats for the time in PHP.

   echo "Following are some of the different"

            . "formats to represent the current time.\n";

   echo date("h:i:s");

   echo PHP_EOL;

   echo date("h.i.s");

   echo PHP_EOL;

   echo date("h.i.s a");

   echo PHP_EOL;

   echo date("H.i.s A");

   echo PHP_EOL;

   echo date("H:i:s a");

   echo PHP_EOL;

   echo date("H.i A");

   echo PHP_EOL;

?>

PHPDate_5.

Converting a Timestamp With getdate() in PHP

As already discussed earlier, a timestamp is a value that is in numeric form and is represented by the number of seconds between 1 January 1970 00:00:00 GMT and the current time in your web server. So, if you want to convert a timestamp into a readable value in terms of hours, minutes, seconds, days, weeks, months, and years, then you can convert it using the getdate() function in PHP.

The getdate() function in PHP takes a parameter timestamp or by default takes the current timestamp and returns the readable information about the timestamp in an array.

Syntax of getdate() in PHP:

// Syntax to get the 

// information about a timestamp

// using the getdate() in PHP.

// pass the timestamp

// whose information you want

getdate($timestamp)

         // or

// this will accept the default timestamp

getdate()

The following example will illustrate the getdate() function in PHP.

<?php

/********** 1. default timestamp ***********/ 

   // store the array returned by

   // the getdate() function for the

   // default timestamp

   // in a variable.

   $defaultTimestamp = getdate(); 

   // print the converted default 

   // timestamp.

   print_r($defaultTimestamp);

   echo PHP_EOL;

?>

PHPDate_6

<?php 

/********** 2. user-defined timestamp ***********/

    $myTimestamp = 25380210;

   // store the array returned by

   // the getdate() function for

   // your timestamp

   // in a variable.

   $convertedTimestamp = getdate($myTimestamp)

   // print the converted default 

   // timestamp.

   print_r($convertedTimestamp);

   echo PHP_EOL;  

?>

PHPDate_7.

Converting a Timestamp With the date() In PHP

The date() function as already discussed above can also be used to get some information about a timestamp in terms of the date. The date() function in PHP represents the date with respect to the timestamp that is specified as a parameter to it. Note that the timestamp takes the default value in case no parameter is passed, here too.

Syntax of date() in PHP:

// syntax for converting a 

// timestamp using the date() function

// in PHP.

date(format,timestamp)

         // or

// to convert the default timestamp

date(format)

The following example will illustrate the date() function to convert a timestamp in PHP.

<?php

   // print the date according to the 

   // current timestamp.

   // The time() function will return 

   // the default current timestamp.

   echo 'The current date and time is: ';

   echo (date("d/m/Y  h:i A\n", time()));

   echo PHP_EOL;

?>

PHPDate_8

PHP mktime() function

The mktime() function is a built-in function provided by PHP. This function is exactly the reverse of the date() function. The mktime() function is used to generate a timestamp for the given date and time. This function accepts arguments that are: hour, minute, second, month, day, year respectively. These parameters are optional. If you do not pass any argument, then the mktime() function will consider the current date and time by default and convert it into a timestamp.

Syntax of mktime() function in PHP.

// syntax to create a timestamp

// using the mktime() function.

mktime(hour, minute, second, month, day, year)

The following example will illustrate how to create your own timestamp using the mktime() function in PHP.

<?php

   // create you timestamp

   // store it in a variable.

   $myTimeStamp = mktime(20, 22, 40, 11, 25, 2021);

   // Print the timestamp in seconds.

   echo 'The created timestamp in seconds is: ';

   echo PHP_EOL;

   echo 'The date according to the new timestamp is: ';

   echo PHP_EOL;

   // This will print the date 

   // according to the specified timestamp.

   // pass the timestamp variable

   // to the date() function. 

   echo(date("F d, Y h:i:s A", $myTimeStamp));

   echo PHP_EOL;

?>

PHPDate_9.

Are you a web developer or interested in building a website? Enroll for the Full Stack Web Developer - MEAN Stack Master's Program. Explore the course preview!

Wrapping Up!

In this article, you have learned about PHP Date. You explored PHP date and time functions in depth. You then dived deep into the need for PHP Date function, PHP time function, and the syntax for both the functions used in PHP. You also discussed in detail how we can convert a timestamp with the help of the date() function.

To get started with PHP, you can refer to this video.

Don’t just stop here. To learn MEAN stack development and to give yourself a chance to work for top tech giants, check out our course on Full Stack Web Developer - MEAN Stack. In this course, you will learn some of the hottest skills like Node, Mongo, etc. that will help you to set your foot into professional web development. 

If you have any questions for us, please mention them in the comments section and we will have our experts answer them for you.

Happy Learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.