0

I am trying to measure time difference I am also learning to wright PHP..

I am saving time and date into SQL as datetime by:

 $now = new DateTime();
 $datenow = $now->format('Y-m-d H:i:s');

  $sql = "INSERT INTO Logg ( logdate , Log  , value) VALUES ( '$datenow' , 'Log', '$value' )";

I can now do a query and get:

 $result = mysqli_query( $conn , $sqlq );
  while($row = mysqli_fetch_array($result)) { 
$myLogdate = $row['logdate'];

What I am after, is to be able to check the time between

$myLogdate 

and

$now = new DateTime();
$datenow = $now->format('Y-m-d H:i:s');

I have tried:

$interval = $datenow->diff($myLogdate);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;

But I get no results....

Bergum
  • 77
  • 9

3 Answers3

1

You can use date_diff.

Example from the linked page:

<?php
    $datetime1 = new DateTime('2009-10-11');
    $datetime2 = new DateTime('2009-10-13');
    $interval = $datetime1->diff($datetime2);
    echo $interval->format('%R%a days');
?>

A list of possible formats can be found here

waka
  • 3,362
  • 9
  • 35
  • 54
  • It seems to stop when I use your and the other example. if I add an echo "test"; in the line after, it will not bee shown on the web page. – Bergum Oct 13 '17 at 06:23
  • @Bergum: If it just stops, there is an error somewhere else. You have to check your PHP error logs to see if there is a warning or an error. – waka Oct 13 '17 at 06:46
  • Found One: PHP Warning: date_diff() expects parameter 1 to be DateTimeInterface, string given in – Bergum Oct 13 '17 at 07:10
  • Found the error, now how to fix it. What I get from $myLogdate = $row['logdate']; is in the wrong format. How can i fix it? – Bergum Oct 13 '17 at 07:39
  • @Bergum: `$myLogdate` seems to be a string, as suggested to by the error message, so you need to convert it to `DateTime`: `$datetime = new DateTime($myLogDate);` – waka Oct 13 '17 at 07:41
  • 1
    YES! Thank you. That was the answer. Now I have the solution to many problems.. :-) – Bergum Oct 13 '17 at 07:49
0

for finding the date difference try the below code:

$interval = date_diff($datenow, $myLogdate);
echo $interval->format('%R%a days')

and for format the interval (like "%R%a" means +days) follow http://php.net/manual/en/dateinterval.format.php.

Mahesh
  • 64
  • 3
  • No. it's something else. Can it be an error with $myLogdate and $datenow not being the same type of text/string/whatever? – Bergum Oct 13 '17 at 06:21
  • Yupp $myLogdate = $row['logdate']; gives me the wrong format. Any tips on how to handle it? – Bergum Oct 13 '17 at 07:40
0

The solution provided by waka was:

$then = new DateTime($myLogDate);
$interval = date_diff($now, $then);
echo $interval->format('%R%a days');
Bergum
  • 77
  • 9