简体   繁体   中英

format mysql timestamp using php

i have column named postDate defined as timestamp. when i print it directly:

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:

echo date('F/j/Y',$result['postDate'])

i get December/31/1969

what am i doing wrong?

many thanks

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.

date('F/j/Y',$result['postDateInt']);

The PHP date function looks for an int time() as the 2nd param. Try using strtotime()

echo date('F/j/Y', strtotime($result['postDate']) );

为什么不在MySQL查询中根据需要格式化日期?

SELECT DATE_FORMAT(postDate, '%M/%D/%Y') as date from table

The PHP `date()' function expects a number for the second parameter - ie a unix timestamp.

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.

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:

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:

echo date('F/j/Y',$result['mydatefield_timestamp']);

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM