How to Subtract current date time from date time in database - PHP

php time difference in minutes
php subtract minutes from datetime
php calculate time difference between two dates in hours and minutes
php time difference in seconds
php time difference in hours
php subtract date from today
calculate days between two dates in php
php subtract days from date

I'm working on a project.I have to check " how many minutes ago ,user updated the database " .For that I used following code :

<?php
include('connect_db.php');

$sql  =" SELECT * FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ;    

$result = $conn->query($sql);

if ($result->num_rows > 0) {

    
    while($row = $result->fetch_assoc()) {  

       $time = strtotime($row['time_']);

       $current=time();

       $sub_time=$current-$time;

     echo $sub_time;
}

You can just change your select statement to give you the time difference in seconds as shown below:

$sql  =" select UNIX_TIMESTAMP(current_Timestamp()) - UNIX_TIMESTAMP(time_) FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ; 

How to Subtract Time from Current DateTime in PHP, Subtract time from date - Use date() and strtotime() functions to subtract time (​hours, minutes, and seconds) form current DateTime using PHP. On the other hand, the strtotime() function converts string formatted DateTime into Unix timestamp. You can use these two functions together to subtract time form current date using PHP. Subtract Hours from Datetime Use the following code snippet to subtract 2 hours from current date and time using PHP.

I think DateTime is better approach, as it has the methods to achieve the result you need.

maybe something like this:

$time=$row['time_'];
$curr_time=new DateTime();
$difference=$time->diff($curr_time);

http://php.net/manual/en/class.datetime.php

DateTime::sub - Manual, DateTime::sub -- date_sub — Subtracts an amount of days, months, years, hours CAUTION: Never subtract months from the current day, always do so from the  CAUTION: Never subtract months from the current day, always do so from the 1st of the month. Let us imagine that it is May 31, 2019, so 2019-05-31, the function will not give 2019-04-31 because April is not 31 days old but 30, it will create problems.

You first need to convert them to timestamp. And them subtract them convert the resuting timestamp back to format you want.

    while($row = $result->fetch_assoc()) {  

       $time = strtotime($row['time_']);

       $current=time();
       $sub_time=date('d-m-y h:i:s',(strototime(date('d-m-y h:i:s')-$time));
       echo $sub_time;
}

You need to handle the greater than and less than cases too.

DateTime::diff - Manual, DateTime::diff -- DateTimeImmutable::diff -- DateTimeInterface::diff -- date_diff the object on which diff is called is subtracted from the object that is passed to diff. I think this is because "now" is the current time, while "tomorrow" is the current (I was comparing now against time in database and exif metadata in photos). The following is an easy way to use PHP to deduct an hour from the present date and time. Use the date feature to set the date format, then use strtotime to return it.You may also like How to Subtract Minutes to Date and Time in PHP and How to Add Hours to Date and Time in PHP.

Updated

You should use the DateTime functions to figure out the difference in time. You should be able to integrate this into your code.

I incorporated my suggested code as a function into your original code. This should work for you.

Try this:

function timeDiff($date){

  $date     = new DateTime(date('Y-m-d H:i:s', strtotime($date)));
  $current  = new DateTime(date('Y-m-d H:i:s'));
  $interval = $date->diff($current);
  return $interval->format('%H:%I:%S');


}

include('connect_db.php');

$sql  ="SELECT * FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ;    

$result = $conn->query($sql);

  if ($result->num_rows > 0) {


      while($row = $result->fetch_assoc()) {  

         echo timeDiff($row['time_']);
  }

}

PHP date_sub() Function, PHP date_sub() Function. ❮ PHP Date/Time Reference. Example. Subtract 40 days from the 15th of March, 2013: <?php The DateInterval class was introduced in PHP version 5.3.0 and its purpose is to represent a date interval. In the example above, we set the DateInterval object to P1D, which means a period of one day. We then subtracted that interval from the current date. If you wanted to subtract five days instead of one day, then you would use P5D instead of P1D.

How to subtract 30 days from the current datetime in MySQL?, To subtract 30 days from current datetime, first we need to get the information about current date time, then use the now() method from MySQL. When getting the difference between two DateTime objects with fractions of seconds, DateTime::diff() works under PHP 7.1. However, under PHP 5.6, the fraction is truncated. It's not clear whether the truncation happens when getting the DateTime objects' values, during the calculation, or immediately before returning the result.

Subtract hours from a time and date using PHP., //Get the current timestamp. $currentTime = time(); //The number of hours that you want //to subtract from the date and time. $hoursToSubtract  You can use PHP date() function or DateTime() class to get current Date & Time in PHP. This tutorial will help you to get current date time in PHP. The provided results based on the timezone settings in the php.ini file. You may need to modify this setting to get date and time in the required timezone.

MySQL 5.7 Reference Manual :: 12.6 Date and Time , TIMESTAMPDIFF(), Subtract an interval from a datetime expression Functions that return the current date or time each are evaluated only once per query at  DateTime Arithmetic. The following examples show some pitfalls of DateTime arithmetic with regard to DST transitions and months having different numbers of days. Example #1 DateTime::add/sub add intervals which cover elapsed time. Adding PT24H over a DST transition will appear to add 23/25 hours (for most timezones).

Comments
  • Your code seems fine, but I'm not sure strtotime() can understand your date-time format. The PHP manual is not very helpful: php.net/manual/en/datetime.formats.compound.php I don't see yours there. Why not cut the last bit off, and use the MySQL format? So you're left with this bit: 2018-07-14 11:42:21.
  • The time() function returns the date in UTC. If your database time is in local time, use date() instead.
  • stackoverflow.com/questions/10907750/…