PHP date and time date() function



PHP Date and Time

The date and time values are very important in any programming language. In this PHP tutorial we will discuss some ready made PHP date time function.

PHP supports date() function and getdate() function used for returning date values. In this PHP tutorial we will learn PHP  date() function and next php tutorial we will learn getdate() function in detail.


 The PHP date() function

The PHP date() function is mostly used method of returning date values.

PHP date() syntax:

date(format, timestamp);

  • format : Specifies the format of timstamp
  • timestamp : Specifies a timestamp, default timestamp is current date and time

The format parameter of the date() function specifies the format of the date. The returning date format depend on the format parameter, the format parameter is compulsory required parameter in date() function, while the timestamp parameter is optional.

PHP date() function Example

For display simple dates we use some characters like day(d), month(m), year(y).

  • d – for day of month in digit (01 to 31)
  • m – for month in digit (01 to 12)
  • y – for year in two digit (15)
  • D – for day of week in three character (Sat)
  • M – for month in character (Aug)
  • Y – for year in four digit (2015)
  • l – for full day of week (Saturday)
  • F – for full month name (August)
  • a – for ‘am’ or ‘pm’ in lowercase
  • A – for ‘AM’ or ‘PM’ in uppercase
  • L – for leap year (1 for yes, 0 fro no)
  • z – day of year (0 – 365)

PHP date() function example

<?php

echo "Today is = ". date('d-m-Y'). "<br>";;
echo "Today is = " . date("Y/m/d") . "<br>";
echo "Today is = " . date("Y-m-d") . "<br>";

?>

The output of above example date() function example is :

Today is = 20-08-2015
Today is = 2015/08/20
Today is = 2015-08-20

Exmaple date() function

<?php

echo "The days = " . date("l") . "<br>";;
echo "The days = " . date("D") . "<br>";
echo "The month = " . date("M") . "<br>";
echo "The year = " . date("Y") . "<br>";
echo "The month = " . date("F") . "<br>";
echo "Time = " . date("a");

?>

The output is :

The days = Thursday
The days = Thu
The month = Aug
The year = 2015
The month = August
Time = am

Now we use date() function for displays times.

The characters used to display times.

  • h – for 12 hour format
  • H – for 24 hour format
  • s – for hour seconds
  • i – for hour minutes (0 – 59)

PHP example for display times

<?php

echo "The time = " .date('h:i:s a');

?>

The output is like :

The time = 09:25:28 am

Leave a Reply

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