简体   繁体   中英

Calculate time between now() and timestamp field - MySQL or PHP?

I have a timestamp field named ending . I want to calculate the time between now and that.

Here's what I'm trying but result simply says blob

select item_id, CONCAT(
FLOOR(HOUR(TIMEDIFF(now(), ending)) / 24), ' days, ',
MOD(HOUR(TIMEDIFF(now(), ending)), 24), ' hours, ',
MINUTE(TIMEDIFF(now(), ending)), ' minutes')
AS TimeDiff from items where item_id=39

Or should I use PHP instead? They are both used extensively on the page... I'm working on the assumption that as I'm already doing a query then to include it in that is more efficient than another PHP call - but, I could be wrong!

UPDATE I made a fiddle for this and it works perfectly, so why would my results within MySQL Workbench say blob ?

This is the table explained:

item_id int(11) NO  PRI     auto_increment
user_id int(11) YES         
title   varchar(128)    YES         
price   decimal(10,2)   YES         
category    int(11) YES         
cat_parent  int(11) YES         
description varchar(1024)   YES         
item_condition  int(11) YES         
delivery    varchar(45) YES         
ending  timestamp   YES         
postcode    varchar(12) YES         
latitude    float(10,6) YES         
longitude   float(10,6) YES         
dateadded   timestamp   YES     CURRENT_TIMESTAMP   

put SELECT at the start of your query?

SELECT CONCAT(
    FLOOR(HOUR(TIMEDIFF(now(), '2012-08-02 11:20')) / 24), ' days, ',
    MOD(HOUR(TIMEDIFF('2012-08-05 09:56', '2012-08-02 11:20')), 24), ' hours, ',
    MINUTE(TIMEDIFF('2012-08-05 09:56', '2012-08-02 11:20')), ' minutes, ',
    SECOND(TIMEDIFF('2012-08-05 09:56', '2012-08-02 11:20')), ' seconds')
AS TimeDiff

returns 34 days, 22 hours, 36 minutes, 0 seconds

You also can use this query -

SELECT
  CONCAT(
    TIMESTAMPDIFF(DAY, ending, NOW()), ' days ',
    TIME_FORMAT(TIMEDIFF(TIME(NOW()), TIME(ending)), '%k hours %i minutes')
  ) TimeDiff
FROM items;

About the BLOB type - that is because of different data types values which are used in CONCAT function, to avoid this, use CAST or CONVERT functions, eg -

SELECT
  CAST(
    CONCAT(
      TIMESTAMPDIFF(DAY, ending, NOW()), ' days ',
      TIME_FORMAT(TIMEDIFF(TIME(NOW()), TIME(ending)), '%k hours %i minutes')
    ) AS CHAR
  )
  TimeDiff
FROM items;

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