In PHP, date() function allows to get date, time or both in a specified format.

Syntax

date(format, timestamp);
formatGet date time or both as per given format
timestampIt is optional, current date time is default if not specified.

Date Format

dGives month day number( 01-31 )
DGives Day name (Mon,Tue,Wed…)
mGives month number(1-12)
MGives month name (Jan,Feb,Mar,Apr…)
yGives last two digit of year
YGives years four digit
lGives Week number
LGives complete day name (Monday, Tuesday, Wednesday…)

Time Format

hGives time 12 hour format (01-12)
HGives time 24 hour format (01-24)
iGives minutes (0-59)
sGives seconds (0-59)
aGives (am/pm) antemeridian and post meridian in lowercase
AGives (AM/PM) antemeridian and post meridian in uppercase

Get Date

<?php

 echo date("d-m-y");
 echo '<br/>';

echo date("d/M/Y");
 echo '<br/>';

echo date("Y-m-d");
 echo '<br/>';

?>
  1. Any seperator like – or / etc can be used to separate date month and Year.
  2. In any order d,m,y etc can be used.

Get Time

<?php

//Only hour minute and seconds
 echo date("h-i-s a");
 echo '<br/>';

//Only hour minute and AM/PM
echo date("H-i A");
 echo '<br/>';

?>

Same as date, time h,i,s,a,A etc can be use in any order and any separator can be used to separate h,i,s etc.

Get Date and Time in PHP

<?php

 echo date("d-m-Y h-i-s a");

?>

mktime()

It take at least one parameter, and returns the Unix timestamp for a given date time. It is calculated from Unix Epoch (January 1 1970 00:00:00 GMT) and the given date time and given number of seconds passed.

Syntax

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

Example


<?php

echo mktime(10); // hour
echo '<br/>';
echo mktime(10,15); // hour minute 
echo '<br/>';
echo mktime(10,15,40); // hour minute second
echo '<br/>';
echo mktime(10,15,40,2); // hour minute second month
echo '<br/>';
echo mktime(10,15,40,2,5); // hour minute second month day year
echo '<br/>';
echo mktime(10,15,40,2,5,2024); // hour minute second month day year
echo '<br/>';

?>

Convert mktime() in date time

<?php
$dt=mktime(10,15,40,2,5,2024);
echo "Created date is " . date("d-m-Y h:i:sa", $dt);
?>

Get and Set timezone

Most of the times, your php script returns wrong date and time because of different timezone, PHP allows to get current time zone and to set timezone also. PHP returns server time zone.

Get time zone

date_default_timezone_get() returns the default time zone. It do not accept any parameters.

<?php
 echo date_default_timezone_get();
 echo date("d-m-Y h-i-s a");
?>

Set time zone

To set time zone in PHP use, date_default_timezone_set(‘Europe/London’);

<?php
date_default_timezone_set('Asia/Kolkata');
echo date("d-m-Y h-i-s a");
?>