This PHP code example shows how to get and print current dates and times in different formats. It uses the PHP date() function to get the formatted date string and displays the commonly used date-time format to understand it easily.



Example:

<?php
//Check what time zone the server is currently in
$Timezone = date_default_timezone_get();
echo "The current server timezone is: " . $Timezone."\n\n";

//Set default timezone
//date_default_timezone_set('America/Los_Angeles'); //USA: Pacific
//date_default_timezone_set('America/Chicago'); //USA: Central
//date_default_timezone_set('America/New_York'); //USA: Eastern
date_default_timezone_set('Asia/Kolkata'); //Asia: India

//Prints the current date something like (2022-05-04)
echo date('Y-m-d')."\n";

//Prints the current time something like (19:13:51)
echo date('H:i:s')."\n";

//MySQL DATETIME format
//Prints the current date-time something like (2022-05-04 19:13:51)
echo date('Y-m-d H:i:s')."\n";

//Prints the current date something like (2022/05/04)
echo date('Y/m/d')."\n";

//Prints the current date something like (04/05/2022)
echo date('d/m/Y')."\n";

//Prints something like (Wednesday 4th of May 2022 07:13:51 PM)
echo date('l jS \of F Y h:i:s A')."\n";

//Prints something like (Wednesday)
echo date("l")."\n";

//Prints something like (19:13pm)
echo date('G:ia')."\n";

//Use of predefined constants in format parameter (Wed, 04 May 2022 19:13:51 +0530)
echo date(DATE_RFC2822)."\n";

//Prints something like (May 4, 2022, 7:13 pm)
echo date("F j, Y, g:i a")."\n";

//Prints something like (05.04.22)
echo date("m.d.y")."\n";

//Prints something like (05,4,2001)
echo date("j,n,Y")."\n";

//Prints something like (20220504)
echo date("Ymd")."\n";

//Prints something like (It is the 4th day.)
echo date('\I\t \i\s \t\h\e jS \d\a\y.')."\n";

//Prints something like (Wed May 4 19:22:06 IST 2022)
echo date("D M j G:i:s T Y")."\n";
?>

Program Output:

The current server timezone is: UTC

2022-05-04
19:40:47
2022-05-04 19:40:47
2022/05/04
04/05/2022
Wednesday 4th of May 2022 07:40:47 PM
Wednesday
19:40pm
Wed, 04 May 2022 19:40:47 +0530
May 4, 2022, 7:40 pm
05.04.22
4,5,2022
20220504
It is the 4th day.
Wed May 4 19:40:47 IST 2022


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram