Reputation: 125
I have a database row whose type is "timestamp". It automatically populates each time a new record has been added with the time of that record's insertion. Right now for one of the records it holds the value:
2010-06-19 18:40:51
I tried to turn this in to a more user friendly format by:
$timeStamp = $row['date'];
$timeStamp = date( "m/d/Y", $timeStamp);
But it returns this:
12/31/1969
I read somewhere that the date function can only be used on unix timestamps, perhaps what I have in my database isn't a proper timestamp and I need to convert it to one first before using the date function on it (?). What is the solution?
Upvotes: 12
Views: 47778
Reputation: 6992
SELECT UNIX_TIMESTAMP(sql_row_with_timestamp) AS some_much_more_readable_name FROM your_table
should do the trick.
Upvotes: 1
Reputation: 382881
Use strtotime function:
$timeStamp = $row['date'];
$timeStamp = date( "m/d/Y", strtotime($timeStamp));
For the date from your example 2010-06-19 18:40:51
, it would return:
06/19/2010
The timestamp
field updates automatically but you can disable that behavior by changing it to DEFAULT CURRENT_TIMESTAMP
otherwise it will auto update. From the manual:
In a CREATE TABLE statement, the first TIMESTAMP column can be declared in any of the following ways:
With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses, the column has the current timestamp for its default value, and is automatically updated.
With neither DEFAULT nor ON UPDATE clauses, it is the same as DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.
With a DEFAULT CURRENT_TIMESTAMP clause and no ON UPDATE clause, the column has the current timestamp for its default value but is not automatically updated.
Upvotes: 23
Reputation: 19561
strtotime($timeStamp)
(string to time) is what you want to convert into a unix timestamp.
Then you can use the date on that, so something like date( "m/d/Y", strtotime($timeStamp) )
http://php.net/manual/en/function.strtotime.php
Upvotes: 2