Ashburn, April 29, 2017

How To Synchronize Timezones in PHP and MySQL

How To Synchronize Timezones in PHP and MySQL
How To Synchronize Timezones in PHP and MySQL

In this tutorial I will show you how to synchronize timezones in PHP and MySQL.

Luckily, you can do it by adding a few lines of codes to your PHP MySQL application.

Use the following snippet:


date_default_timezone_set('America/New_York');

$now = new DateTime();
$mins = $now->getOffset() / 60;
$sgn = ($mins < 0 ? -1 : 1);
$mins = abs($mins);
$hrs = floor($mins / 60);
$mins -= $hrs * 60;
$offset = sprintf('%+d:%02d', $hrs*$sgn, $mins);

//Your DB Connection - sample
$db = new PDO('mysql:host=localhost;dbname=test', 'dbuser', 'dbpassword');
$db->exec("SET time_zone='$offset';");

You will need to replace ‘America/New_York‘ by your desired timezone.

Thus, you might also find helpful to check the whole PHP list of supported timezones.

The PHP and MySQL timezones are now synchronized within your PHP application. No need to go for php.ini or MySQL console!

I hope it helps you!

Cheers!

About Karlos Maldonado 36 Articles
Computer Sciences Engineer graduated from Florida Atlantic University (FAU) in Boca Raton, Florida. Has gotten great experience in the IT and Web Development industry working for companies such as SIRIUS XM RADIO, 4MEDIA as well as collaborating with local companies.

Be the first to comment

Leave a Reply

Your email address will not be published.