如何使用 PHP 将 MySQL 时间转换为 UNIX 时间戳?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4577794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:32:44  来源:igfitidea点击:

How to convert MySQL time to UNIX timestamp using PHP?

phpmysqltimestamp

提问by daGrevis

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

有很多关于“UNIX 时间戳到 MySQL 时间”的问题。我需要相反的方式,是的...知道吗?

回答by UltraInstinct

Use strtotime(..):

使用strtotime(..)

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

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

还要检查一下(以 MySQL 的方式进行。)

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

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

回答by Sarfraz

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

您可以UNIX_TIMESTAMP直接从您的查询中使用mysql 的功能,这是一个示例:

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

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

同样,您可以传入日期/日期时间字段:

SELECT UNIX_TIMESTAMP(yourField);

回答by Florian Mertens

From one of my other posts, getting a unixtimestamp:

从我的其他帖子中获得一个 unixtimestamp:

$unixTimestamp = time();

Converting to mysql datetime format:

转换为mysql日期时间格式:

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

Getting some mysql timestamp:

获取一些 mysql 时间戳:

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

Converting it to a unixtimestamp:

将其转换为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:

Unix 时间戳也更安全。在检查(例如)之前的范围检查之前,您可以执行以下操作来检查 url 传递的变量是否有效:

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

回答by psycho brm

$time_PHP = strtotime( $datetime_SQL );

回答by Kai Noack

Instead of strtotimeyou should use DateTimewith PHP. You can also regard the timezone this way:

而不是strtotime你应该使用DateTimePHP。你也可以这样看待时区:

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

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

$mysqltime是 MySQL Datetime 类型,例如2018-02-26 07:53:00

回答by mintedsky

Slightly abbreviated could be...

稍微缩写可以是...

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