MySQL第二次格式化日期时间

时间:2015-06-26 12:22:43

标签: php mysql

如何在mysql中将第二个转换为格式化的日期时间?我有一个查询来获得第二个日期差异。即

 SELECT TIMESTAMPDIFF(SECOND, '2012-06-03 13:13:55', '2012-06-06 15:20:18') sec

现在我需要在SQL中将这个秒转换为日期时间。可能吗?或者mysql中是否有任何函数可以使DATETIME字段与格式化选项(如

)区别开来
SELECT DATEDIFF('%m %D, %Y %H...', '2012-06-03 13:13:55', '2012-06-06 15:20:18') sec

所以我的预期结果是1 mon 5 day 13 hour 3 sec

3 个答案:

答案 0 :(得分:1)

这似乎有效

SELECT 
TIMESTAMPDIFF(SECOND, '2012-06-03 13:13:55', '2012-06-06 15:20:18') secs,
TIMESTAMPDIFF(MINUTE, '2012-06-03 13:13:55', '2012-06-06 15:20:18')  mins,
TIMESTAMPDIFF(HOUR, '2012-06-03 13:13:55', '2012-06-06 15:20:18')  hours,
TIMESTAMPDIFF(DAY, '2012-06-03 13:13:55', '2012-06-06 15:20:18')  days,
TIMESTAMPDIFF(MONTH, '2012-06-03 13:13:55', '2012-06-06 15:20:18')  months,
TIMESTAMPDIFF(YEAR, '2012-06-03 13:13:55', '2012-06-06 15:20:18')  years

给出结果行

secs    mins    hours   days    months  years
266783  4446    74      3       0       0

您现在可以使用这些结果做任何您喜欢的事情

您现在可以使用秒结果列来创建输出,如下所示: -

<?php
// of course get this from the result set not a hard coded value
$secs = 266783;
$days = date('d', $secs);

$secs -= $days*24*60*60;
$hours = date('H', $secs);

$secs -= $hours*60*60;
$mins = date('m', $secs);

$secs -= $mins*60;
$seconds = date('s', $secs);

echo sprintf('%d Days %d Hours %d Minutes %d Seconds', $days, $hours, $mins, $seconds );

这将输出

4 Days 2 Hours 12 Minutes 23 Seconds

答案 1 :(得分:0)

查看此功能date_format(date, format) {{3}}

答案 2 :(得分:0)

我想你想要这个。这里的默认日期指定'2008-01-02'。

SELECT DATE_ADD('2008-01-02', INTERVAL TIMESTAMPDIFF(SECOND, '2012-06-03 13:13:55', '2012-06-06 15:20:18') SECOND);