[英]Is there an easy way to get a Unix timestamp from an SQL timestamp in php?
My database table has a column that contains SQL timestamps (eg. 2009-05-30 19:43:41). 我的数据库表有一个包含SQL时间戳的列(例如2009-05-30 19:43:41)。 I need the Unix timestamp equivalent (an integer) in my php program.
我的php程序需要Unix时间戳等效项(整数)。
$posts = mysql_query("SELECT * FROM Posts ORDER BY Created DESC");
$array = mysql_fetch_array($posts);
echo $array[Created];
Where it now echoes the SQL timestamp, I want a Unix timestamp. 现在它在哪里回显SQL时间戳,我想要一个Unix时间戳。 Is there an easy way to do this?
是否有捷径可寻?
strtotime()
will happily take a SQL timestamp and convert it to UNIX time: strtotime()
会很高兴地获取一个SQL时间戳并将其转换为UNIX时间:
echo strtotime($array['Created']);
Note that it is bad practice to not use quotes around your array keys. 请注意,不对数组键使用引号是一种不好的做法。 According to the docs :
根据文档 :
Always use quotes around a string literal array index.
始终在字符串文字数组索引周围使用引号。 For example, $foo['bar'] is correct, while $foo[bar] is not.
例如,$ foo ['bar']是正确的,而$ foo [bar]不是。
This is wrong, but it works.
这是错误的,但是可以。 The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes).
原因是此代码具有未定义的常量(bar),而不是字符串(“ bar”-注意引号)。 PHP may in future define constants which, unfortunately for such code, have the same name.
PHP将来可能会定义常量,不幸的是,对于此类代码,它们具有相同的名称。 It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string.
之所以起作用,是因为PHP自动将裸字符串(不与任何已知符号相对应的未加引号的字符串)转换为包含裸字符串的字符串。 For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.
例如,如果没有定义的名为bar的常量,则PHP将替换字符串“ bar”并使用它。
Given a regular datetime field, you can do this in query with the MySQL function UNIX_TIMESTAMP (): 给定一个常规的datetime字段,您可以使用MySQL函数UNIX_TIMESTAMP ()在查询中执行此操作:
$posts = mysql_query("SELECT *
, UNIX_TIMESTAMP(Created)
FROM Posts
ORDER BY Created DESC");
you also should know that the PHP function mysql_fetch_array returns both numeric associative keys for a query result. 您还应该知道PHP函数mysql_fetch_array返回查询结果的两个数字关联键。 I find this redundant, so I like to be more more specific and use:
我发现这是多余的,因此我想更具体地使用:
$array = mysql_fetch_array($posts, MYSQL_ASSOC);
Also, and as @Paolo Bergantino indicated, quoting your echo would be a good decision: 而且,正如@Paolo Bergantino指出的那样,引用您的回声将是一个不错的决定:
echo $array['Created'];
One last comment, you're using "SELECT *" -- it is worth reading discussion on the pros and cons of "SELECT *" syntax . 最后一条评论,您正在使用“ SELECT *”- 值得阅读有关“ SELECT *”语法优缺点的讨论 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.