PHP Echo Tutorials

Date and Time in PHP

Written by phpecho.com   

PHP provides a variety of date and time command variances which makes it very versatile. The entire command structure is very modular which means that you will be able to get only the date, only the day or a combination. In fact, there are a large number of combinations possible using the date and time functions. In this tutorial, we will show how to use these and also a list of all the available functions.

The first example, we use shows how to print the current date and time to the console (the browser in our case).

<?php print date("Y:m:d");  ?>

This will output the current date separating the year, month and date by “:” symbol.

We can also get the same output using the following syntax:

<?php print  date("Y").":".date("m").":".  date("d"); ?>

As you will notice from the above, PHP allows you to use each part of the date separately as well as together. That is the power of the date and time command in PHP. Using the above, you can create a multitude of features for your web applications. For example, suppose you want to welcome your user in a grandiose way. The below example is an option:

<?php
   print (‘Welcome  ‘.$userName);
   print(‘Today is  the ‘.date(“d”).”th day of   the“.date(“m”).”th month of “.date(“Y”).” year”);
   ?>

The below table gives a list of all available parameters for this function.

Code used

Meaning/Output

<?php print date("a"); ?>

"am" or "pm"

<?php print  date("A"); ?>

"AM" or "PM"

<?php print  date("d"); ?>

Day of the month: 01 to 31

<?php print  date("D"); ?>

Day of the week: Sun, Mon, Tue, Wed, Thu, Fri, Sat

<?php print date("F"); ?>

Month: January, February, March, April, May..

<?php print  date("h"); ?>

Hour: 01 to 12

<?php print  date("H"); ?>

Hour: 00 to 23

<?php print  date("g"); ?>

Hour: 1 to 12

<?php print  date("G"); ?>

Hour: 0 to 23

<?php print  date("i"); ?>

Minutes: 00 to 59

<?php print  date("j"); ?>

Day of the month: 1 to 31

<?php print  date("l"); ?>

Day of the week: Sunday, Monday, Tuesday, Wednesday..

<?php print  date("L"); ?>

1 for leap year; 0 for non-leap year

<?php print  date("m"); ?>

Month: 01 to 12

<?php print  date("n"); ?>

Month: 1 to 12

<?php print  date("M"); ?>

Month: Jan, Feb, Mar, Apr, May, Jun..

<?php print  date("s"); ?>

Seconds: 00 to 59

<?php print  date("S"); ?>

Ordinal: 1st, 2st, 3st, 4st...

<?php print  date("t"); ?>

Number of days in the month: 28 to 31

<?php print  date("U"); ?>

Seconds since 1970/01/01 00:00:00

<?php print  date("w"); ?>

Day of the week: 0 (Sunday) to 6 (Saturday)

<?php print  date("Y"); ?>

Year (four digits)

<?php print  date("y"); ?>

Year (two digits)

<?php print  date("z"); ?>

Day of the year: 0 to 365

<?php print  date("Z"); ?>

Difference in seconds from Greenwich meridian