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

daG*_*vis 71 php mysql timestamp

有很多问题要问'UNIX时间戳到MySQL时间'.我需要相反的方式,是的......任何想法?

Ult*_*nct 133

用途strtotime(..):

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

另外检查一下(用MySQL方式做).

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

  • 使用strtotime时要小心时区.看到这个问题:http://stackoverflow.com/questions/10417179/is-the-result-of-strtotime-is-changed-based-on-the-timezone (4认同)

Sar*_*raz 52

您可以UNIX_TIMESTAMP直接从查询中获取mysql的功能,这里有一个例子:

SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');
Run Code Online (Sandbox Code Playgroud)

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

SELECT UNIX_TIMESTAMP(yourField);
Run Code Online (Sandbox Code Playgroud)


Flo*_*ens 10

从我的其他帖子中获取unixtimestamp:

$unixTimestamp = time();
Run Code Online (Sandbox Code Playgroud)

转换为mysql日期时间格式:

$mysqlTimestamp = date("Y-m-d H:i:s", $unixTimestamp);
Run Code Online (Sandbox Code Playgroud)

获取一些mysql时间戳:

$mysqlTimestamp = '2013-01-10 12:13:37';
Run Code Online (Sandbox Code Playgroud)

将其转换为unixtimestamp:

$unixTimestamp = strtotime('2010-05-17 19:13:37');
Run Code Online (Sandbox Code Playgroud)

...将其与一个或一个范围进行比较,以查看用户是否输入了实际时间:

if($unixTimestamp > strtotime("1999-12-15") && $unixTimestamp < strtotime("2025-12-15"))
{...}
Run Code Online (Sandbox Code Playgroud)

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

if(ctype_digit($_GET["UpdateTimestamp"]))
{...}
Run Code Online (Sandbox Code Playgroud)


psy*_*brm 6

$time_PHP = strtotime( $datetime_SQL );
Run Code Online (Sandbox Code Playgroud)

  • 问题是如何将$ mysql_timestamp转换为$ php_timestamp,答案是"strtotime"执行它,如图所示.有什么可以解释的? (4认同)
  • 对**为什么**这个回答问题的一些解释会使答案更有用.*(我知道可能有很多其他的一行答案,但它们并没有被添加)* (2认同)

Kai*_*ack 5

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

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

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