Set timezone in PHP and MySQL

前端 未结 6 1367
闹比i
闹比i 2020-11-30 04:29

I am making an application where I need to store th date in MySQL using the PHP date() function.



        
相关标签:
6条回答
  • 2020-11-30 04:39

    For PHP use this function:

    date_default_timezone_set()
    

    MySQL:

    default-time-zone='timezone'
    

    If you have the root privilege, you can set the global server time zone value at run-time with this statement:

    SET GLOBAL time_zone = timezone;
    

    Per-connection time zones. Each client that connects has their own time zone setting, given by the session time_zone variable. Initially, the session variable takes its value from the global time_zone variable, but the client can change its own time zone with this statement:

    SET time_zone = timezone;
    
    0 讨论(0)
  • 2020-11-30 04:40

    In PHP:

    <?php
    define('TIMEZONE', 'Europe/Paris');
    date_default_timezone_set(TIMEZONE);
    

    For MySQL:

    <?php
    $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';");
    

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

    This is from this article on SitePoint.

    0 讨论(0)
  • 2020-11-30 04:49

    I can change my mysql default timezone from variable section by editing row which says "time zone" in phpmyadmin.

    Here you can also change format and lot more you can find in mysql support http://dev.mysql.com/doc/refman/5.7/en/time-zone-support.html, I hope its help you.

    You can put same timezone for both php and mysql.

    0 讨论(0)
  • 2020-11-30 04:52

    The best method Set timezone in PDO MySQL:

    If appropriate, whether by mistake you can use: date('P') Example:

    new PDO('mysql:host=localhost;dbname=nametable', 
     'username', 
     'password', 
     [PDO::MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8;SET time_zone = '".date('P')."'"]);
    
    0 讨论(0)
  • 2020-11-30 04:55

    You can do it easily just by the following two lines of PHP.

    $tz = (new DateTime('now', new DateTimeZone('Asia/Kabul')))->format('P');
    $pdo->exec("SET time_zone='$tz';");
    
    0 讨论(0)
  • 2020-11-30 04:55

    The best method Set timezone in PDO MySQL:

    new PDO('mysql:host=localhost;dbname=nametable', 'username', 'password', [PDO::MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8;SET time_zone = 'Europe/Rome'"]);

    0 讨论(0)
提交回复
热议问题