user2052241
user2052241

Reputation: 81

Format DATETIME from MYSQL database using PHP

So I have a field in my database called 'DateTime' and the following lines of code:

echo "Date/Time: ";
echo $row['DateTime'];

How do I format it so that instead of being like this:'2013-02-07 22:14:56', it will be like this: '07/02/13 - 22:14'

Thanks.

Upvotes: 1

Views: 10503

Answers (7)

Amol
Amol

Reputation: 343

$timestamp contains ur date & time in any format.....................

date('Y/m/d - H:i',strtotime($timeStamp));

Upvotes: 1

jassicagugu
jassicagugu

Reputation: 11

how to output date into Year textbox Month textbox Day textbox

$book_date = $myrow["Publication_Day"];
$book_year = Date("Y", strtotime($book_date));

Upvotes: 1

John Conde
John Conde

Reputation: 219934

Here's an alternative using DateTime. If you're working with timezones this code can be easily modified to handle that.

$datetime = new DateTime('2013-02-07 22:14:56');
echo $datetime->format('d/m/y H:i');

See it in action

Upvotes: 0

spencer7593
spencer7593

Reputation: 108510

Another alternative would be to have MySQL format the DATETIME value as a string in the desired format, using the DATE_FORMAT function.

SELECT DATE_FORMAT(`DateTime`,'%d/%m/%y - %H:%i') AS `DateTime`
   ...

No change required to your PHP code except for the SQL text sent to the database server.

This approach can very efficient, and reduce the amount of code you need, if all you are doing with this string is displaying it. If you are doing any sort of manipulation on this value, then casting the string value returned from MySQL resultset into a datetime object is probably a better way to go.


A demonstration of the DATE_FORMAT function:

SELECT DATE_FORMAT('2013-02-07 22:14:56','%d/%m/%y - %H:%i') AS `DateTime`

DateTime
----------------
07/02/13 - 22:14

Upvotes: 2

JDavies
JDavies

Reputation: 21

Alternatively you could use: DateTime::createFromFormat('Y/m/d H:i:s',$row['DateTime']); this will give you a datetime object, which are quite nice to work with.

Upvotes: 1

rinchik
rinchik

Reputation: 2670

$mytime = strtotime('2013-06-07 22:14:56');
$newDate = date('m/d/y - G:i', $mytime);
echo $newDate;

Upvotes: 0

Dallin
Dallin

Reputation: 590

echo date('d/m/y H:i', strtotime($row['DateTime']));

See date and strtotime for more detail on the functions from the docs

Upvotes: 0

Related Questions