php 使用php格式化mysql时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5339339/
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
format mysql timestamp using php
提问by daniel.tosaba
i have column named postDate
defined as timestamp.
when i print it directly:
我有一个名为postDate
时间戳的列。当我直接打印时:
echo $result['postDate'];
i do get that what is stored(eg. 2011-03-16 16:48:24
)
on the other hand when i print it through date function:
2011-03-16 16:48:24
另一方面,当我通过日期函数打印它时,我确实得到了存储的内容(例如):
echo date('F/j/Y',$result['postDate'])
i get December/31/1969
我明白了 December/31/1969
what am i doing wrong?
我究竟做错了什么?
many thanks
非常感谢
回答by DhruvPathak
try this.
尝试这个。
date('F/j/Y',strtotime($result['postDate']));
as timestamp is required, not formatted date as second parameter. or you can also try
因为时间戳是必需的,而不是格式化日期作为第二个参数。或者你也可以试试
SELECT UNIX_TIMESTAMP(postDate) as postDateInt from myTable
instead of SELECT postDate from myTable
and then have this in your code.
而不是SELECT postDate from myTable
然后在您的代码中使用它。
date('F/j/Y',$result['postDateInt']);
回答by Aaron W.
The PHP datefunction looks for an int time()
as the 2nd param. Try using strtotime()
PHP日期函数寻找一个int time()
作为第二个参数。尝试使用strtotime()
echo date('F/j/Y', strtotime($result['postDate']) );
回答by Wige
Why not format the date as needed in your MySQL query?
为什么不在 MySQL 查询中根据需要格式化日期?
SELECT DATE_FORMAT(postDate, '%M/%D/%Y') as date from table
回答by Spudley
The PHP `date()' function expects a number for the second parameter - ie a unix timestamp.
PHP `date()' 函数需要一个数字作为第二个参数 - 即一个 unix 时间戳。
You can convert a SQL date string (or virtually any other date string) into a timestamp in PHP by using the strtotime()
function. At least two other answers have already suggested this.
您可以使用该strtotime()
函数将 SQL 日期字符串(或几乎任何其他日期字符串)转换为 PHP 中的时间戳。至少有两个其他答案已经提出了这一点。
However, I would suggest that you'd be better off getting the date out of your database in unix timestamp format in the first place. You can do this by querying using the MySQL UNIX_TIMESTAMP()
function, as follows:
但是,我建议您最好首先以 unix 时间戳格式从数据库中获取日期。您可以通过使用 MySQLUNIX_TIMESTAMP()
函数进行查询来完成此操作,如下所示:
SELECT UNIX_TIMESTAMP(mydatefield) AS mydatefield_timestamp FROM mytable
..obviously, replacing the field and table names as appropriate.
..显然,适当地替换字段和表名。
Then you will get the date in timestamp format in your returned dataset in PHP, which you can pass directly into the date()
function as follows:
然后,您将在 PHP 中返回的数据集中获取时间戳格式的日期,您可以直接将其传递到date()
函数中,如下所示:
echo date('F/j/Y',$result['mydatefield_timestamp']);
Hope that helps.
希望有帮助。