简体   繁体   中英

Show only the time from mySQL timestamp field using PHP

When I echo['time'] from the Database i get for example

2012-07-21 17:00:00

my question is how should I show only the hours and minutes for every timestamp I get? (17:00)

You can select it as:

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

or use strtotime as mentioned in other answers.

If you did want the full time with seconds, you could also use:

SELECT TIME(`dateColumn`) FROM ...

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

You should parse it properly and echo what you want with the DateTime class:

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

Demo

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

but It is better practice to process from MySQL if possible,

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

shoul retrieve the data and format it to you good to go!

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

或者您可以使用datetime函数在sql查询中进行格式化

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

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

  <?php
$ct= date('Y-m-d 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. Simply include the file in the other php file where you want to display the time in the format
    1 day ago/ 30 day ago.....sec ago..hrs ago..month ago and many more..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM