28

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

4 Answers 4

65

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']);
Sign up to request clarification or add additional context in comments.

2 Comments

Hm, well done you beat me to the punch. +1 for you. I also recommended UNIX_TIMESTAMP(). When I started my answer you only had the strtitime() but, but by the time I posted it you'd added the SQL bit as well.
Doesn't strtotime() take timezones into account when formatting, and mistakenly treat the UTC unix date string as being in the timezone set by PHP?
11

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

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

Comments

8

Why not format the date as needed in your MySQL query?

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

1 Comment

that seems to be by far the easiest solution :D
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.