pedro
pedro

Reputation: 504

dates difference

I have two dates in the mysql table.

sample:
date1: 2011-01-01 06:40:00
date2: 2011-02-19 18:00:00

I need to return the difference between them, like this:

50 days, 12 hours, 20 minutes

How can i do this in PHP or MYSQL?

Upvotes: 3

Views: 184

Answers (4)

Edoardo Pirovano
Edoardo Pirovano

Reputation: 8334

This code should do what you need:

<?php
$result = mysql_query("SELECT (date1, date2) FROM myTable;");
while (list($date1, $date2) = mysql_fetch_array($result)) {
    $firstdate = new DateTime($date1);
    $seconddate = new DateTime($date2);
    $diff = $firstdate->diff($seconddate);
    echo $diff->d . " days, " . $diff->h . " hours, " . $diff->i . "minutes\n";
}
?>

Upvotes: 4

Nick Pavluk
Nick Pavluk

Reputation: 379

You can read about mysql DATEDIFF function: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff

Upvotes: 0

Ovais Khatri
Ovais Khatri

Reputation: 3211

Check MySQL date calculations.

Upvotes: 0

Gowri
Gowri

Reputation: 16835

try this,

SELECT CONCAT(
FLOOR(TIMESTAMPDIFF(HOUR,'2011-01-01 06:40:00', '2011-02-19 18:00:00')  / 24), ' days ',
MOD(TIMESTAMPDIFF(HOUR,'2011-01-01 06:40:00', '2011-02-19 18:00:00'), 24), ' hours ',
MINUTE(TIMESTAMPDIFF(second,'2011-01-01 06:40:00', '2011-02-19 18:00:00')), ' minutes')

Upvotes: 3

Related Questions