//Convert string to unix timestamp
strtotime( "04/05/2014" );

//Insert into database, convert from unix timestamp first
$sql = "INSERT INTO database ( date ) VALUES ( FROM_UNIXTIME(:date) )";

It's saving to database as 2014-04-04 15:00:00 when I expect it to be 2014-04-05 00:00:00

What am I doing wrong?

有帮助吗?

解决方案 2

A Unix timestamp is a fixed moment in time. However, MM/DD/YYYY dates are relative pieces of data that depend on time zone.

When you do this:

strtotime( "04/05/2014" );

... you tell PHP to calculate the timestamp that corresponds to midnight in PHP time zone. You then do this:

FROM_UNIXTIME(:date)

... and tell MySQL to calculate the local time (regarding MySQL time zone) that correspond to the timestamp. Thus the shift.


Time zone conversions in SQL are difficult so I'd avoid them at all cost. I'd feed MySQL with a string that already contains the appropriate local time, e.g.: 2014-04-05 or 2014-04-05 00:00:00. That string is easy to calculate from PHP.

As about PHP, either set the time zone explicitly:

$ts = strtotime( "04/05/2014 +02:00" );

... or adjust the default zone to your liking:

date_default_timezone_set('Europe/Madrid');

I'd also recommend you get familiar with the DateTime class—it's way more powerful than good old timestamps.

其他提示

date_default_timezone_set('America/Los_Angeles');

becouse of this set your timezone and it will work


Enjoy :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top