开发者

Current timestamp in PHP and MySQL

I am using PHP to print the current timestamp using time() and I have a MySQL column which stores the date, which I am converting to a times开发者_如何学运维tamp using strtotime(). However, when I print the converted values, I have a one hour difference between them. The real difference is in seconds. What's wrong?


Assuming they both run on the same physical server, it is probably a timezone mismatch.

You can check the timezone on your MySQL server by running the following query in the MySQL console:

SELECT @@global.time_zone;

And on your PHP page by running a script with:

echo date_default_timezone_get();

Once you figure out which one is wrong, you should be able to fix this by editing my.cnf or php.ini.

You can also change the default timezone on runtime using date_default_timezone_set().


Set your timezone before inserting your times

date_default_timezone_set('America/Los_Angeles'); // Whatever your timezone is

mysql_query("INSERT
            INTO table
            (date)
            VALUES
            (" . time() . ")") or die(mysql_error());


You may want to use the PHP strftime function, as it does take local timezones into account. You may be running into a daylight savings time issue.


Use MySQL's UNIX_TIMESTAMP() function to get the current epoch time:

INSERT INTO mytable SET tstamp = UNIX_TIMESTAMP();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜