MySQL Timestamp Difference

橙三吉。 提交于 2020-01-12 06:39:27

问题


I have a table with column timestam which stores a timestamp with this format: "2012-12-10 21:24:30"

I am looking for a SQL Query that takes the current timestamp and subtracts it with the one in the column and gives the difference in this format:

"3 Hours and 2 mins Remaining"

Looking for a MySQL Query that does that.


回答1:


use TIMESTAMPDIFF

TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)

where unit argument, which should be one of the following values: MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.

my approach : set unit as SECOND and then use SEC_TO_TIME

SELECT SEC_TO_TIME(TIMESTAMPDIFF(SECOND,`table`.`time_column`,CURRENT_TIMESTAMP()))

// will return in hh:mm:ii format

update

Return yes if HourDifference are less than 48 hours? otherwise no

SELECT IF(TIMESTAMPDIFF(HOUR,`time_column`,CURRENT_TIMESTAMP())< 48  ,'yes','no')



回答2:


Assume your table name is 'testtable'

Table create query is given below

CREATE TABLE `testtable` (
    `id` INT(2) NOT NULL AUTO_INCREMENT,
    `period` TIMESTAMP NULL DEFAULT NULL,
    PRIMARY KEY (`id`)
)

Insert some data to test my query. Query to insert some data is given below

INSERT INTO `testtable` (`id`, `period`) VALUES
    (1, '2012-12-10 17:21:09'),
    (2, '2012-11-06 18:21:12'),
    (3, '2012-12-06 18:21:18'),
    (4, '2012-12-06 19:21:24'),
    (5, '2012-12-06 18:21:27');

Now execute following query to get your answer

SELECT *, 
       CONCAT(HOUR(difftime), ' hours ', MINUTE(difftime), ' Minutes ', 
       SECOND(difftime), ' seconds remaining') AS timetaken 
FROM   (SELECT *, 
               SEC_TO_TIME(UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP( 
               ttable.period)) AS 
                      diffTime 
        FROM   testtable ttable) AS temptable1 

Output is given below

The column 'timetaken' will display answer.



来源:https://stackoverflow.com/questions/13813675/mysql-timestamp-difference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!