Mostrando entradas con la etiqueta timezone. Mostrar todas las entradas
Mostrando entradas con la etiqueta timezone. Mostrar todas las entradas

martes, 19 de abril de 2011

PHP and MySQL timezones


<?php
define('TIMEZONE', 'America/New_York');
We'll use that to set PHP's default timezone:

date_default_timezone_set(TIMEZONE);
What about MySQL? It's possible to set its default timezone at the start of every session -- I'd recommend doing it after you've connected to the database. The command is:

SET time_zone='offset';
where offset is a string value representing the difference to UTC/GMT, e.g. '-4:00', '+3:00', '+10:30', etc. Note that the +/- sign is essential -- even for zero -- and timezone offsets are not necessarily a whole hour. So let's write a little PHP to parse the timezone offset and format a string MySQL can understand. First, we'll create a new DateTime object, find the offset in seconds, and convert it to minutes:

$now = new \DateTime();
$mins = $now->getOffset() / 60;
We can now calculate whole hours and minutes. The first line determines whether the offset is positive or negative, then converts the value to a positive number to make the calculation easier:

$sgn = ($mins < 0 ? -1 : 1);
$mins = abs($mins);
$hrs = floor($mins / 60);
$mins -= $hrs * 60;

PHP's sprintf function can then be used to format the string:

$offset = sprintf('%+d:%02d', $hrs*$sgn, $mins);
Finally, we execute the SET time_zone command. The following lines provide an example, but you should use your own database library where possible:

$db = new \PDO('mysql:host=localhost;dbname=test',

  'dbuser',
'dbpassword');
$db->exec("SET time_zone='$offset';");
The PHP and MySQL timezones are now synchronized within your application.