Sugs
Sugs

Reputation: 65

Subtract fetched datetime from current date time

I need to calculate the time difference between the localDatetime and a Datetime fetched from a specific row in my database-table(csv) called ReportedDateAndTime. I searched a lots of solutions but it doesn't working for me. Displaying localtime & the fetched time from Database are working. But the time difference doesn't. Here is my code so far. Please help. Thanks in advance!

<?php

    include_once('connection.php');
    $sql="SELECT * FROM csv";
    $records=mysqli_query($conn, $sql);
    $date = new DateTime(null, new DateTimeZone('Asia/Colombo'));
    while ($csv=mysqli_fetch_assoc($records))
    {
    $exp = $csv['ReportedDateAndTime'];
    }
    $diff = $date->diff($exp);
    echo $diff->format('%H')

?>

Upvotes: 0

Views: 218

Answers (2)

Sugs
Sugs

Reputation: 65

Thanks all. Fortunately I found an answer. :)

<?php
include 'connection.php';
date_default_timezone_set('Asia/Colombo');
$the_time = date('H:i');
echo $the_time." </br>";
$sql="SELECT ReportedDateAndTime FROM csv";
$result=$conn->query($sql);
while ($row = $result->fetch_assoc()) 
{
$new_time=$row['ReportedDateAndTime'];
echo "<br/>";
echo $new_time." ReportedDateAndTime</br>";
$datetime1 = new DateTime($the_time);
$datetime2 = new DateTime($new_time);
$interval = $datetime1->diff($datetime2);
$hours=$interval->format('%h');
$minutes= $interval->format('%i');
echo "<br/>";
echo $hours." Hours  ".$minutes."  Minutes</br></br>";
}
?>

Upvotes: 1

Drew
Drew

Reputation: 24960

From the mysql doc

SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');

'2004-01-01 13:00:00'

SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');

'2004-01-01 22:00:00'

https://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html

Upvotes: 1

Related Questions