PcRestorer PcRestorer - 3 months ago 10
PHP Question

How can I change the timezone of the date I'm inserting into my database?

When I insert a timestamp into my database the value is about 10 hours back from my local time. The database is hosted on Godaddy's server.

I have changed my php5.ini file and added

date.timezone = 'Europe/Istanbul'


(it was america/phoenix as default) when I checked with
phpinfo();


Then I ran this code:

if (date_default_timezone_get()) {
echo 'date_default_timezone: '. date_default_timezone_get() .'<br />';
}

if (ini_get('date.timezone')) {
echo 'date.timezone: ' . ini_get('date.timezone');
echo date("d/m/y : H:i:s", time());
}


It's OK also same as my local time

But when i insert data it's get America/Phoenix timestamp which is -10 hours from my local time

Here is my insert code

$insertSQL = sprintf("INSERT INTO cepbank (username, trans_id, bank, tutar, operator) VALUES ('$username', '$trans_id', '$bank', '$tutar', '$operator')");


and here is my MySql Table

CREATE TABLE `cepbank` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(11) collate utf8_turkish_ci NOT NULL,
`trans_id` int(11) NOT NULL,
`bank` varchar(11) collate utf8_turkish_ci NOT NULL,
`tutar` decimal(10,2) NOT NULL,
`operator` varchar(32) collate utf8_turkish_ci NOT NULL,
`tarih` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci COMMENT='CepBank Gelen' AUTO_INCREMENT=143 ;

Answer

It happens because you use default CURRENT_TIMESTAMP for tarih field. And it uses the unadjusted server date. Get the adjusted timestamp in php:

$timestamp = date('Y-m-d H:i:s', time ());

then add it into the query:

INSERT INTO cepbank 
    (tarih, username, trans_id, bank, tutar, operator)
VALUES 
    ('$timestamp','$username', '$trans_id', '$bank', '$tutar', '$operator'
Comments