Brandon Wilson
Brandon Wilson

Reputation: 4590

Calculate Timespan in MySQL

I am trying to query a table that has dates in it. I would like to take the date from the table and compare it with the current time. I would like to see something like this.

2011.10.05 10:12:50 - Date time table
Current date

I need it to say 1 day 14 mins 13 secs.

I thought about using datesub() in the query but it does not give me what I want. Is there a way to accomplish this in the query, if not I need to take another route. I even read through the manual but I could not find anything regarding timespan.

$query = "select country, rprice as regPrice, mprice as midPrice, pprice as prePrice, saddress as streetAddress,
                _id as ID, lat, lng, sname as Name, logo, admin_level_1 as state, locale as city, rdate as regDate, 
                mdate as midDate, pdate as preDate, 
                format((acos(sin(radians($lat1)) * sin(radians(lat)) + cos(radians($lat1)) *
                cos(radians(lat)) * cos(radians($lng1) - radians(lng))) * 6378),1) as distance from stationDetails where 
                (acos(sin(radians($lat1)) * sin(radians(lat)) + cos(radians($lat1)) * cos(radians(lat)) * 
                cos(radians($lng1) - radians(lng))) * 6378) <= $rad order by $sort asc, $type asc";

This query works, but I need to take rdate, mdate, and pdate and convert it to time since it was updated in the database. @RolandoMySQLDBA query works well just like I wanted it but for some reason when I put it into the above query it breaks and tells me that I have in my SQL syntax.

EDIT: Here is what I came up with after tweaking a few things and learning how to write functions.

DELIMITER $$

DROP FUNCTION IF EXISTS `GetTimeDisplay2` $$

CREATE FUNCTION `GetTimeDisplay2` (GivenTimestamp TIMESTAMP)

RETURNS VARCHAR(32)

DETERMINISTIC

BEGIN    

    DECLARE rv VARCHAR(32);

    DECLARE diff BIGINT;    

    SET diff = UNIX_TIMESTAMP()-UNIX_TIMESTAMP(GivenTimestamp);

        IF diff < 0 THEN

        SET rv = CONCAT(abs(diff/60),' From Now');

    END IF;

    IF diff = 0 THEN

        SET rv = 'Just Now';

    END IF;

    IF diff = 1 THEN

        SET rv = '1 sec ago';

    END IF;

    IF diff BETWEEN 2 AND 60 THEN

        SET rv = CONCAT(FORMAT(diff, 0), ' secs ago');

    END IF;

    IF diff BETWEEN 120 AND 3599 THEN

        SET rv = CONCAT(FORMAT(diff/60, 0), ' mins ago');

    END IF;

    IF diff BETWEEN 61 AND 119 THEN

        SET rv = CONCAT(FORMAT(diff/60, 0), ' min ago');

    END IF;

    IF diff = 3600 THEN

        SET rv = CONCAT(FORMAT(diff/3600, 0), ' hr ago');

    END IF;

    IF diff BETWEEN 3601 AND 86399 THEN

        SET rv = CONCAT(FORMAT(diff/3600, 0), ' hrs ago');

    END IF;

    IF diff > 86400 THEN

        SET rv = DATE_FORMAT(GivenTimestamp, '%a %l:%i %p');

    END IF;

    IF diff > 259200 THEN

        SET rv = DATE_FORMAT(GivenTimestamp, '%b %e at %l:%i %p');

    END IF;

    RETURN rv;

END $$

DELIMITER ;

Upvotes: 1

Views: 3578

Answers (1)

RolandoMySQLDBA
RolandoMySQLDBA

Reputation: 44363

This query will display the exact days, hours, minutes, and seconds from Feb 1, 2011 Midnight:

SELECT 
    TRIM(REPLACE(CONCAT(
        IF(dy=0,'',IF(dy=1,'1 day ',CONCAT(dy,' days '))),
        IF(hr=0,'',IF(hr=1,'1 hr ', CONCAT(hr,' hrs  '))),
        IF(mn=0,'',IF(mn=1,'1 min ',CONCAT(mn,' mins '))),
        IF(sc=0,'',IF(sc=1,'1 sec ',CONCAT(sc,' secs ')))),'  ',' '))
    TimeDisplay
FROM (SELECT dy,hr,mn,MOD(sec_aaaa,60) sc
FROM (SELECT dy,hr,FLOOR((sec_aaa - dy*86400 - hr*3600)/60) mn,sec_aaa sec_aaaa
FROM (SELECT dy,FLOOR((sec_aa - (dy*86400))/3600) hr,sec_aa sec_aaa
FROM (SELECT FLOOR(sec_a/86400) dy,sec_a sec_aa
FROM (SELECT (UNIX_TIMESTAMP() - UNIX_TIMESTAMP('2011-02-01 00:00:00')) sec_a)
A) AA) AAA) AAAA) B;

Just replace the '2011-02-01 00:00:00' with any datetime value or table column name you want.

Give it a Try !!!

UPDATE 2011-10-06 13:38 EDT

I wrote a stored function you can call that will handle this for you:

DELIMITER $$

DROP FUNCTION IF EXISTS `test`.`GetTimeDisplay` $$
CREATE FUNCTION `test`.`GetTimeDisplay` (GivenTimestamp TIMESTAMP)
RETURNS VARCHAR(32)
DETERMINISTIC
BEGIN

    DECLARE rv VARCHAR(32);
    DECLARE diff BIGINT;

    SET diff = UNIX_TIMESTAMP() - UNIX_TIMESTAMP(GivenTimestamp);
    SELECT
        TRIM(REPLACE(CONCAT(
            IF(dy=0,'',IF(dy=1,'1 day ',CONCAT(dy,' days '))),
            IF(hr=0,'',IF(hr=1,'1 hr ', CONCAT(hr,' hrs  '))),
            IF(mn=0,'',IF(mn=1,'1 min ',CONCAT(mn,' mins '))),
            IF(sc=0,'',IF(sc=1,'1 sec ',CONCAT(sc,' secs ')))),'  ',' '))
    INTO rv
    FROM (SELECT dy,hr,mn,MOD(sec_aaaa,60) sc
    FROM (SELECT dy,hr,FLOOR((sec_aaa - dy*86400 - hr*3600)/60) mn,sec_aaa sec_aaaa
    FROM (SELECT dy,FLOOR((sec_aa - (dy*86400))/3600) hr,sec_aa sec_aaa
    FROM (SELECT FLOOR(sec_a/86400) dy,sec_a sec_aa
    FROM (SELECT ABS(UNIX_TIMESTAMP() - UNIX_TIMESTAMP(GivenTimestamp)) sec_a)
    A) AA) AAA) AAAA) B;

    IF diff = 0 THEN
        SET rv = '0 secs';
    END IF;
    IF diff < 0 THEN
        SET rv = CONCAT(rv,' From Now');
    END IF;
    IF diff > 0 THEN
        SET rv = CONCAT(rv,' Ago');
    END IF;

    RETURN rv;

END $$

DELIMITER ;

You can rewrite the query like this:

$query = "select country, rprice as regPrice, mprice as midPrice, pprice as prePrice, saddress as streetAddress,
                _id as ID, lat, lng, sname as Name, logo, admin_level_1 as state, locale as city, test.GetTimeDisplay(rdate) as regDate, 
                test.GetTimeDisplay(mdate) as midDate, test.GetTimeDisplay(pdate) as preDate, 
                format((acos(sin(radians($lat1)) * sin(radians(lat)) + cos(radians($lat1)) *
                cos(radians(lat)) * cos(radians($lng1) - radians(lng))) * 6378),1) as distance from stationDetails where 
                (acos(sin(radians($lat1)) * sin(radians(lat)) + cos(radians($lat1)) * cos(radians(lat)) * 
                cos(radians($lng1) - radians(lng))) * 6378) <= $rad order by $sort asc, $type asc";

You may want to move the stored function to another database. The code I have puts the stored function in the test database.

Give it a Try !!!

Upvotes: 1

Related Questions