在 PHP 中将 TIMESTAMP 转换为 unix 时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2850624/
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
Converting TIMESTAMP to unix time in PHP?
提问by Rob
Currently I store the time in my database like so: 2010-05-17 19:13:37
目前我将时间存储在我的数据库中,如下所示: 2010-05-17 19:13:37
However, I need to compare two times, and I feel it would be easier to do if it were a unix timestamp such as 1274119041. (These two times are different)
但是,我需要比较两次,我觉得如果它是1274119041. (这两个时间不同)
So how could I convert the timestamp to unix timestamp? Is there a simple php function for it?
那么如何将时间戳转换为 unix 时间戳呢?有没有简单的php函数?
回答by Mark
You're looking for strtotime()
您正在寻找strtotime()
回答by Florian Mertens
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 webbiedave
If you're using MySQL as your database, it can return date fields as unix timestamps with UNIX_TIMESTAMP:
如果您使用 MySQL 作为数据库,它可以使用UNIX_TIMESTAMP将日期字段作为 unix 时间戳返回:
SELECT UNIX_TIMESTAMP(my_datetime_field)
You can also do it on the PHP side with strtotime:
您也可以使用strtotime在 PHP 端执行此操作:
strtotime('2010-05-17 19:13:37');
回答by ax.
if you store the time in the database, why don't you let the database also give you the unix timestamp of it? see UNIX_TIMESTAMP(date), eg.
如果您将时间存储在数据库中,为什么不让数据库也给您它的unix时间戳?见UNIX_TIMESTAMP(date),例如。
SELECT UNIX_TIMESTAMP(date) ...;
databases can also do date and time comparisons and arithmetic.
数据库还可以进行日期和时间比较和算术。

