Show only time from timestamp mySQL field using PHP

When I echo['time'] from the database, I get, for example,

 2012-07-21 17:00:00 

My question is: how do I show only hours and minutes for each timestamp I receive? (5 p.m.)

+4
source share
6 answers

You can choose it as:

 SELECT TIME_FORMAT(`dateColumn`, '%H:%i') FROM ... 

or use strtotime as indicated in other answers.

If you want to get the full time in seconds, you can also use:

 SELECT TIME(`dateColumn`) FROM ... 

See http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

+10
source

You must parse it correctly and respond to the DateTime class:

 $time = '2012-07-21 17:00:00'; $date = DateTime::createFromFormat( 'Ymd H:i:s', $time, new DateTimeZone( 'America/New_York')); echo $date->format( 'H:i'); // Will print 17:00 

Demo

+5
source

You could do what Chris said echo date('H:i', strtotime('2012-07-21 17:00:00'));

but it's best to handle MySQL if possible

select date_format(time, '%H:%i') from table;

shoul extracts the data and formats it well for you!

+3
source

echo date('H:i', strtotime($row['time']));

or you can format in your sql query using datetime functions

+1
source
 echo date('H:i', strtotime('2012-07-21 17:00:00')); 
0
source

I use my own code. try this .. follow these steps: -
1. Select the time from the database table under the assumption: - $ time = $ row ['time'];
2. create a php file with the name: - "time.php"
3. paste the following code into time.php

  <?php $ct= date('Ymd H:i:s'); $now = new DateTime("$ct"); $ref = new DateTime("$time"); $diff = $now->diff($ref); $y=$diff->y; $m=$diff->m; $d=$diff->d; $h=$diff->h; $i=$diff->i; $s=$diff->s; if($m>12) { echo $y; echo " year ago"; } elseif($m<1 && $d<1 && $h<1 && $i<1 && $s<60) { echo $s; echo " sec ago"; } elseif($m<1 && $d<1 && $h<1 && $i<60) { echo $i; echo " mins ago"; } elseif($m<1 && $d<1 && $h<48) { echo $h; echo " hrs ago"; } elseif($m<1 && $d<30 && $h<24) { if($d==1) { echo 24+$h." hrs ago"; } else { echo $d; echo " days ago"; } } elseif($m<=12) { if($m > 0) { echo $m; echo " Month ago"; } else { echo $d; echo " days ago"; } } ?> <?php include "time.php";?> //use include/require function where you want to display time ago... 
  1. Just include the file in another php file where you want to display the time in format
    1 day ago / 30 days ago ..... sec ago..hrs ago..month ago and many more ..
0
source

All Articles