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 timestamp 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?
-
What's your timezone setting in PHP, and what's the timezone setting in MySQL? There is your answer.Wrikken– Wrikken2011-08-02 22:27:24 +00:00Commented Aug 2, 2011 at 22:27
-
Bet the server you're running the commands on (or the mysql config) is an hour off.Noah– Noah2011-08-02 22:27:57 +00:00Commented Aug 2, 2011 at 22:27
-
@Wrikken: Could have earned you at least 10 points if you posted that as an answer.GolezTrol– GolezTrol2011-08-02 22:28:15 +00:00Commented Aug 2, 2011 at 22:28
4 Answers
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().
Comments
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());
Comments
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.
Comments
Use MySQL's UNIX_TIMESTAMP() function to get the current epoch time:
INSERT INTO mytable SET tstamp = UNIX_TIMESTAMP();