The PHP Date() Function

PHP date() function is use to convert a timestamp to a more readable date and time.

PHP date() function to you can convert formats a timestamp to a more readable date and time.

Syntax :

date(format,timestamp)

format : Required. Specifies the format of the timestamp

timestamp : Optional. Specifies a timestamp. Default is the current date and time

Example :

<?php
    echo date("d/m/Y");
?>

The PHP date() function return the current date and time according to the built-in clock of the web server on which the script has been executed.

Get a Date

The required format parameter of the date() function specifies how to format the date.Here are some the date-related formatting characters that are commonly used in format string:

> d - It is represents the day of the month (01 to 31)

> D - It is represent day of the week in text as an abbreviation (Mon to Sun)

> m - It is represents a month (01 to 12)

> M - It is represent month in text, abbreviated (Jan to Dec)

> Y - It is represents a year (in four digits)

> y - It is represent year (in two digits)

Other characters susc as "/", ".", or "-" can also be inserted between the characters to add additional formatting.

<?php
    echo date("d/m/Y") . "<br>";
    echo date("d-m-Y") . "<br>";
    echo date("d.m.Y");
?>

Get a Time

You can use the below characters to format the time string:

> H -It is represent 24-hour format of an hour (00 to 23)

> h -It is represent 12-hour format of an hour with leading zeros (01 to 12)

> i It is represent minutes with leading zeros (00 to 59)

> s It is represent seconds with leading zeros (00 to 59)

> a It is represent Lowercase Ante meridiem and Post meridiem (am or pm)

> A It is represent uppercase Ante meridiem and Post meridiem (AM or PM)

The below output the current time in the specified format :

<?php
    echo date("h:i:sa");
?>

The PHP time() Function

The time() function is used to get the current timestamp.

<?php
    echo time();
?>

You can convert timestamp to a human readable date through passing it to the previously introduce date() function.

<?php
    $timestamp = time();
    echo(date("d-m-Y", $timestamp));
?>

Get Your Time Zone

For Example : Sets the timezone to "Asia/Calcutta"", then outputs the current time in the specified format:

<?php
    date_default_timezone_set("Asia/Calcutta");
    echo date("h:i:sa");
?>