Tuesday 20 August 2013

To set the time zone correctly before putting data into a database:

http://www.sitepoint.com/synchronize-php-mysql-timezone-configuration/

http://www.php.net/manual/en/timezones.asia.php


    try
    {
        $DBH = new PDO("mysql:host=hostedresource.com;dbname=somedb", "dbusername", "dbpassword");
        $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }   
    catch(PDOException $e)
    {
        print "db error db_connection_10";
        file_put_contents('PDOErrors.txt', "\ntesting 10 " . $e->getMessage() . "\n", FILE_APPEND);       
        DIE();
    }
   
   
    define('TIMEZONE', 'Asia/Kolkata');
   
    date_default_timezone_set(TIMEZONE);

   
    //SET time_zone='offset';
   
    $now = new DateTime();
   
    $mins = $now->getOffset() / 60;     // for India this will be +5.5hrs or +330 mins (Returns the timezone offset from GMT)
   
    $plus_or_minus = ( $mins < 0 ? -1 : 1 );     // find out if the country is behind or ahead
    $mins = abs( $mins );     // remove the sign
    $hrs = floor( $mins / 60 );     // floor just rounds down to the integer (so for India you will get 5 instead of 5.5)

   
    $mins = $mins - ( $hrs * 60 ); // this gives the minutes component of the timezone offset
   
    $offset = sprintf('%+d:%02d', $hrs*$plus_or_minus, $mins); // sprintf formats the string so that it can be used in the mysql command
   
    $DBH->exec("SET time_zone='$offset';");

No comments:

Post a Comment