MoonEater916
MoonEater916

Reputation: 446

PHP strtotime not performing similar conversion with mysql value

So I am pulling a timestamp from a mysql database and was wondering why none of the timechecks are working.

echo "The time is " . date("Y-m-d h:i:s");
echo "</br>";
echo "Mysql Timestamp " . $row["Uptime"];
echo "</br>";
echo "Mysql Timestamp as strtotime" .strtotime($row["Uptime"]);
echo "</br>";
echo "strtotime Current Time". strtotime("now");
echo "</br>";

the output:

The time is 2018-08-18 12:42:55
Mysql Timestamp 2018-08-18 12:42:52
Mysql Timestamp as strtotime1534596172
strtotime Current Time1534552975

There is about a 4000 difference between the numbers after converting to string. What's going on and how do I fix this without doing x-4000?

Upvotes: 0

Views: 34

Answers (1)

Nick
Nick

Reputation: 147166

The difference is due to your local timezone. date() uses your local timezone to compute the time, while strtotime("now") and time() use UTC time. Compare:

echo "The time is " . date("Y-m-d h:i:s");
echo "</br>";
echo 'strtotime("now") is '. strtotime("now");
echo "</br>";
echo 'strtotime date("Y-m-d h:i:s") is '. strtotime(date("Y-m-d h:i:s"));
echo "</br>";
echo "time() is ". time();
echo "</br>";

Output (in timezone Australia\Adelaide):

The time is 2018-08-17 09:06:35
strtotime("now") is 1534554395
strtotime date("Y-m-d h:i:s") is 1534511195
time() is 1534554395

Now try setting the timezone to UTC:

date_default_timezone_set('UTC');
echo "The time is " . date("Y-m-d h:i:s");
echo "</br>";
echo 'strtotime("now") is '. strtotime("now");
echo "</br>";
echo 'strtotime date("Y-m-d h:i:s") is '. strtotime(date("Y-m-d h:i:s"));
echo "</br>";
echo "time() is ". time();
echo "</br>";

Output - as you can see, all forms return the same value:

The time is 2018-08-18 01:07:21
strtotime("now") is 1534554441
strtotime date("Y-m-d h:i:s") is 1534554441
time() is 1534554441

Upvotes: 2

Related Questions