In PHP, date() function allows to get date, time or both in a specified format.
Syntax
date(format, timestamp);
format | Get date time or both as per given format |
timestamp | It is optional, current date time is default if not specified. |
Date Format
d | Gives month day number( 01-31 ) |
D | Gives Day name (Mon,Tue,Wed…) |
m | Gives month number(1-12) |
M | Gives month name (Jan,Feb,Mar,Apr…) |
y | Gives last two digit of year |
Y | Gives years four digit |
l | Gives Week number |
L | Gives complete day name (Monday, Tuesday, Wednesday…) |
Time Format
h | Gives time 12 hour format (01-12) |
H | Gives time 24 hour format (01-24) |
i | Gives minutes (0-59) |
s | Gives seconds (0-59) |
a | Gives (am/pm) antemeridian and post meridian in lowercase |
A | Gives (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/>';
?>
- Any seperator like – or / etc can be used to separate date month and Year.
- 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");
?>