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?
Summary. The date function in PHP is used to format the timestamp into a human desired format. The timestamp is the number of seconds between the current time and 1st January, 1970 00:00:00 GMT. It is also known as the UNIX timestamp.
Change YYYY-MM-DD to DD-MM-YYYY In the below example, we have date 2019-09-15 in YYYY-MM-DD format, and we will convert this to 15-09-2019 in DD-MM-YYYY format. $orgDate = "2019-09-15"; $newDate = date("d-m-Y", strtotime($orgDate)); echo "New date format is: ".
Answer: Use the strtotime() Function You can first use the PHP strtotime() function to convert any textual datetime into Unix timestamp, then simply use the PHP date() function to convert this timestamp into desired date format. The following example will convert a date from yyyy-mm-dd format to dd-mm-yyyy.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With