Please See UPDATE at the bottom:
I believe your issue is based on the MySQL using a different time zone to your PHP. This will be almost certainly true if your MySQL connection from PHP is not localhost
.
However, even if you are using localhost
, you may have somehow miss-set your MySQL to be using a different time zone to your PHP system.
So first; read this post to get the current timezone of your MySQL, and to output a Hours / Minutes result:
SELECT TIMEP_FORMAT(TIMEDIFF(NOW(), UTC_TIMESTAMP), '%H%i') as MySQLTime
And compare this with your PHP timezone value retrieved from date_default_timezone_get()
and your PHP system time:
print date("r");
Once you've compared and found these are different time values then adjust your MySQL time zone using this answer here .
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';");
UPDATE:
My timezone in php is "Asia/Karachi".
This is your problem. Your MySQL is using UTC and your PHP is using "Asia/Karachi".
So assuming you want to keep your PHP timezone and apply this timezone to your MySQL you need to set the MySQL Timezone, using this excellent answer.
If you can't use the core methods outlined in the link above, then you can do this at script execution time with PDO:
$pdo = new PDO('mysql:host=localhost;dbname=exampletable', 'user',
'pass', [PDO::MYSQL_ATTR_INIT_COMMAND =>"SET time_zone = 'Asia/Karachi'"]);
You will need to manually update all timestamps already set in the DataBase but new timestamps added will be added in the correct timezone.