How to convert MySQL time to UNIX timestamp using PHP?

PhpMysqlTimestamp

Php Problem Overview


There are a lot of questions that ask about 'UNIX timestamp to MySQL time'. I needed the reversed way, yea... Any idea?

Php Solutions


Solution 1 - Php

Use strtotime(..):

$timestamp = strtotime($mysqltime);
echo date("Y-m-d H:i:s", $timestamp);

Also check this out (to do it in MySQL way.)

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp

Solution 2 - Php

You can mysql's UNIX_TIMESTAMP function directly from your query, here is an example:

SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');

Similarly, you can pass in the date/datetime field:

SELECT UNIX_TIMESTAMP(yourField);

Solution 3 - Php

From one of my other posts, getting a unixtimestamp:

$unixTimestamp = time();

Converting to mysql datetime format:

$mysqlTimestamp = date("Y-m-d H:i:s", $unixTimestamp);

Getting some mysql timestamp:

$mysqlTimestamp = '2013-01-10 12:13:37';

Converting it to a unixtimestamp:

$unixTimestamp = strtotime('2010-05-17 19:13:37');

...comparing it with one or a range of times, to see if the user entered a realistic time:

if($unixTimestamp > strtotime("1999-12-15") && $unixTimestamp < strtotime("2025-12-15"))
{...}

Unix timestamps are safer too. You can do the following to check if a url passed variable is valid, before checking (for example) the previous range check:

if(ctype_digit($_GET["UpdateTimestamp"]))
{...}

Solution 4 - Php

$time_PHP = strtotime( $datetime_SQL );

Solution 5 - Php

Instead of strtotime you should use DateTime with PHP. You can also regard the timezone this way:

$dt = DateTime::createFromFormat('Y-m-d H:i:s', $mysqltime, new DateTimeZone('Europe/Berlin'));
$unix_timestamp = $dt->getTimestamp();

$mysqltime is of type MySQL Datetime, e. g. 2018-02-26 07:53:00.

Solution 6 - Php

Slightly abbreviated could be...

echo date("Y-m-d H:i:s", strtotime($mysqltime));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondaGrevisView Question on Stackoverflow
Solution 1 - PhpUltraInstinctView Answer on Stackoverflow
Solution 2 - PhpSarfrazView Answer on Stackoverflow
Solution 3 - PhpFlorian MertensView Answer on Stackoverflow
Solution 4 - Phppsycho brmView Answer on Stackoverflow
Solution 5 - PhpAvatarView Answer on Stackoverflow
Solution 6 - PhpmintedskyView Answer on Stackoverflow