Display the date and time with PHP

by jeremyjones on March 7, 2011

  • Share
  • CevherShare
  • Share
One of the most basic uses of dynamic code on a website is to display the current
date and time. This is a trivial matter with the date() and time() functions as this
code segment demonstrates:

{code type=php}
<?php
// Displays the date as Day, Month Date, Year Time
echo date(“l, F d, Y h:i” ,time());
?>
{/code}

Sometimes it is not sufficient to display the time in just your local time zone. You
might want to display the time somewhere else. In fact, it is common to display the
current time in a few major cities at the same time. You could do this by calculating
the new times on the fly, but the calculations could soon get complicated. Another
way is to use the PEAR Date class that you can download from the internet. This
example uses that class to change the time zone from GTM to Indian Standard
Time:

{code type=php}
<?php
// Start by including the class
include (“Date.php”);
// Initialize the date/time object
$d = new Date(“2006-06-21 10:36:27”);
// Set the time zone to GMT (Greenwich Mean Time)
$d->setTZByID(“GMT”);
// Convert it to IST (Indian Standard Time)
$d->convertTZByID(“IST”);
// Display the time in IST
echo $d->format(“%A, %d %B %Y %T”);
?>
{/code}

This can easily be amended to include different time zones according to your needs.

{ 1 comment… read it below or add one }

Manojkumar February 18, 2014 at 7:52 pm

Thanks very useful

Reply

Cancel reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: