获取时间差并将其转换为 MySQL 中的小时?
借助 MySQL 的 timestampdiff() 方法,你可以实现该功能。语法如下所示 −
语法
SELECT ABS(TIMESTAMPDIFF(HOUR,yourColumnName1,yourColumnName2)) as anyVariableName from yourTableName;
为了理解上述语法,我们创建一个表。创建表的查询如下所示 −
mysql> create table DifferenceInHours -> ( -> StartDateTime datetime, -> EndDateTime datetime -> ); Query OK, 0 rows affected (0.59 sec)
使用 insert 命令在表中插入一些记录。查询如下所示 −
mysql> insert into DifferenceInHours values('2018-12-20 10:00:00', '2018-12-19 12:00:00'); Query OK, 1 row affected (0.11 sec) mysql> insert into DifferenceInHours values('2018-12-20 11:00:00', '2018-12-19 11:00:00'); Query OK, 1 row affected (0.16 sec) mysql> insert into DifferenceInHours values('2018-12-20 10:30:00', '2018-12-19 11:00:00'); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表格中的所有记录。查询如下所示 −
mysql> select *from DifferenceInHours;
输出
+---------------------+---------------------+ | StartDateTime | EndDateTime | +---------------------+---------------------+ | 2018-12-20 10:00:00 | 2018-12-19 12:00:00 | | 2018-12-20 11:00:00 | 2018-12-19 11:00:00 | | 2018-12-20 10:30:00 | 2018-12-19 11:00:00 | +---------------------+---------------------+ 3 rows in set (0.00 sec)
以下查询获取时间差(以小时为单位)。查询如下所示 −
mysql> SELECT ABS(TIMESTAMPDIFF(HOUR,StartDateTime,EndDateTime)) as Hour from DifferenceInHours;
以下是显示时间差(以小时为单位)的输出 −
+------+ | Hour | +------+ | 22 | | 24 | | 23 | +------+ 3 rows in set (0.00 sec)
广告