Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show only the time from mySQL timestamp field using PHP

Tags:

php

mysql

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)

like image 465
EnexoOnoma Avatar asked Jul 21 '12 02:07

EnexoOnoma


People also ask

How can I get the only date from a timestamp?

In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column.

How do you display time and date in MySQL?

The CURRENT_TIMESTAMP function in the MySQL database returns the current date and time (i.e. the time for the machine running that instance of MySQL). It is given as a value in the 'YYYY-MM-DD hh:mm:ss' format.

How do I query a timestamp in SQL?

To get a day of week from a timestamp, use the DAYOFWEEK() function: -- returns 1-7 (integer), where 1 is Sunday and 7 is Saturday SELECT dayofweek('2018-12-12'); -- returns the string day name like Monday, Tuesday, etc SELECT dayname(now()); To convert a timestamp to a unix timestamp (integer seconds):

What function finds current time in MySQL?

MySQL NOW() Function The NOW() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH-MM-SS" (string) or as YYYYMMDDHHMMSS.


Video Answer


2 Answers

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

like image 156
drew010 Avatar answered Oct 24 '22 19:10

drew010


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

like image 30
nickb Avatar answered Oct 24 '22 19:10

nickb