confucius
confucius

Reputation: 13327

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 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?

Upvotes: 1

Views: 12312

Answers (4)

Gaurang
Gaurang

Reputation: 1958

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

INSERT INTO mytable SET tstamp = UNIX_TIMESTAMP();

Upvotes: 0

ICL1901
ICL1901

Reputation: 7778

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.

Upvotes: 0

Steve Robbins
Steve Robbins

Reputation: 13822

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());

Upvotes: 2

sagi
sagi

Reputation: 5767

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().

Upvotes: 3

Related Questions