Subtract data php - php

I'm trying to subtract one date on another on PHP, create a new date of 8 hours (08:00:00) and subtract it from the previous result.
I used TIMEDIFF to subtract the first two dates and then DateTime to convert it to date format.
Then I used date_create to create the 8 hours date, in order make the subtraction from the previous result.
The problem is that when I used TIMEDIFF making that last calculation, it returns me the following message:
Catchable fatal error: Object of class DateTime could not be converted to string in /Users/renatoaraujo/Documents/wlib compartilhada/wlib/ponto/index.php on line 50
Where am I missing?
This is my code:
$row = mysqli_query($con, "SELECT TIMEDIFF('".$ponto[0]."','".$ponto[1]."')");
$resultado = mysqli_fetch_array($row);
$datetime = new DateTime($resultado[0]);
$data = date_create('08:00:00');
$row2 = mysqli_query($con, "SELECT TIMEDIFF('".$resultado[0]."', '".$data."'");
$saldo_total = mysqli_fetch_array($row2);

Why are you querying the database for this? You can do everything you need with DateTime.
You could do this as simply as:
$start_time = new DateTime();
$eight_hours_before = $start_time->modify('-8 hours');
Or alternately you could use DateInterval.
$start_time = new DateTime();
$eight_hours = new DateInterval('P8H');
$start_time->sub($eight_hours);

$data is a DateTime, not a string. You need to use date_format() to convert it to a string:
$row2 = mysqli_query($con, "SELECT TIMEDIFF('".$resultado[0]."', '".date_format($data, 'Y-m-d H:i:s)."'");

If your goal is to create a DateTime for 8 hours ago, then this can be done directly in the \DateTime constructor. Something like this:-
$eightHoursAgo = new \DateTime('- 8 hours');
See it working

Related

I need to subtract a mySQL timestamp with a PHP timestamp. Getting a "date_diff() expects parameter 1 to be DateTimeInterface, array given" error

I feel like this should be easy but I have been stuck so long that I am looking for some help from my stackoverflow friends. All I want to do is grab a current timestamp from my mySQL table and subtract it from a current php server timestamp. The mySQL format is
chat_time timestamp current_timestamp()
It looks like this when the insert is completed
2020-06-22 14:51:41
So in my php code I wrote this
//chat countdown logic
$curDate = getdate();
$mysqlTimestamp = $row['chat_time'];
$dif=date_diff($curDate,$mysqlTimestamp);
$row['chat_time'] = $dif;
//end of chat countdown logic
Any idea what I am doing wrong??
Here is how I ended up figuring it out with the advice of the above users.
$dteStart = new DateTime($row['chat_time']);
$dteEnd = new DateTime("now");
$dteDiff = $dteStart->diff($dteEnd);
$row['chat_time'] = $dteDiff->format("%H:%I:%S");
Creating the new DateTime() was the key to sync up the database and php dates in order to use the diff() function.
date_diff() does not accept 2 dates as strings
the manual
So you will have to convert the strings to DateTime object first
// date time now
$curDate = new DateTime();
// make a datetime object from a timestamp
$mysqlTimestamp = (new DateTime)->setTimestamp($row['chat_time']);
$diff = date_diff($curDate, $mysqlTimestamp);
$print_r($diff); // see what you get

date_create and date_diff having issues when I use format or date_format

I have this function that takes in the date for start and end date as a range of dates of looking up reports. I have two tables with different type for start date, but the issue is this lookup must be able to show results from these two tables even the two columns are different from each other. The other table, let's call it table 1, contains the start date in milliseconds; that's how it was set up before. The input for this takes the date of when the reports were uploaded and convert it into milliseconds. The other table, table 2, takes the dates in automatically converts the date into something like this 2019-02-05T11:51:20 format; all start date from table 2 are in this format. This is the format that gets uploaded into the DB. I was told that that's how the android device was doing it, or that's how the input for the start date was written. The end dates for both tables are in milliseconds. I don't know why the end date for table 2 is stored in this format. Looking up reports that are from table 1 is fine. The form gives me the expected results, but when I search for reports from table 2, I get error(s) like
Warning: date_diff() expects parameter 1 to be DateTime, string given in
Fatal error: Call to a member function format() on a non-object in
function dateDifference($date_1, $date_2, $differenceFormat = '%a') // %a
{
$datetime1 = date_create($date_1)->format("Y-m-d\TH:i:s");
//$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$interval = date_diff($datetime1, $datetime2);
return $interval->format($differenceFormat) * 8.64e+7;
}
I have also tried this but same thing.
// function dateDifference2($date_1, $date_2, $differenceFormat = 'Y-m-d\TH:I:s') //Y-m-d\TH:i:s
// {
// $dateTime1 = date_create($differenceFormat, $date_1);
// $dateTime2 = date_create($date_2);
// $interval = date_diff($dateTime1, $dateTime2);
// return $interval->format($differenceFormat) * 8.64e+7;
// }
Can somebody help me out here? Thank you!
NOTE: I can't change the type of dates for this. That's how the two were set up or written. I have no control over that. I can only do things based on what's given to me or what I have. The first app was written by a different group, and so as the second.
There are two issues with this line:
$datetime1 = date_create($date_1)->format("Y-m-d\TH:i:s");
Firstly, date_create expects a string, not a value in milliseconds. You can work around that by using date_timestamp_set and dividing the value by 1000.
Secondly, you are making $datetime1 a string, not a DateTime object by the call to format. You need to remove the ->format("Y-m-d\TH:i:s");
So overall, you should change that first line to this:
$datetime1 = (new DateTime())->setTimeStamp($date_1/1000);
You need to do a similar thing for $datetime2. Note that since $date_1 could be numeric or a date string you need to check for that and change the code appropriately e.g.
function dateDifference($date_1, $date_2, $differenceFormat = '%a') // %a
{
if (is_numeric($date_1))
$datetime1 = (new DateTime())->setTimeStamp($date_1/1000);
else
$datetime1 = new DateTime($date_1);
$datetime2 = (new DateTime())->setTimeStamp($date_2/1000);
$interval = $datetime1->diff($datetime2);
return $interval->format($differenceFormat) * 8.64e+7;
}
Demo on 3v4l.org

Having a hard time understanding how to manipulate date and time in PHP

I'm really not grasping how dates and times get formatted in PHP for use in mathematical equations. My goal is this;
Get a date and time from the database;
// Get array for times in
$sth = mysqli_query($conn,"SELECT * FROM ledger ORDER BY ID");
$timeins = array();
while($r = mysqli_fetch_assoc($sth)) {
$timeins[] = $r["timein"];
//OR
array_push($timeins, $r['timein']);
}
And then find the distance between the current time and the variable in the array, $timeins[0], and then put the minutes, hours, and days difference in separate simple variables for later use. These variables will be used on their own in if statements to find out if the person has passed certain amounts of time.
edit: the format of the dates being returned from the DB is in the default TIMESTAMP format for MySQL. E.g. 2018-08-06 17:38:37.
It is also possible to perform datetime operations in SQL, to get a difference between two datetime/timestamp values in days, hours, minutes... We can use expressions in the SELECT list, to return the results as columns in the resultset.
Ditching the SELECT * pattern, and specifying an explicit list of expressions that we need returned:
$sql = "
SELECT t.id
, t.timein
, TIMESTAMPDIFF(DAY ,t.timein,NOW()) AS diff_days
, TIMESTAMPDIFF(HOUR ,t.timein,NOW()) AS diff_hours
, TIMESTAMPDIFF(MINUTE ,t.timein,NOW()) AS diff_minute
FROM ledger t
ORDER BY t.id ";
if( $sth = mysqli_query($conn,$sql) ) {
// execution successful
...
} else {
// handle sql error
}
You should use the DateTime class in PHP to do any date manipulation. You can convert a string representation of a MySQL format time to a PHP DateTime object using
$date = DateTime::createFromFormat('Y-m-d H:i:s', $mysqldate);
Also you can create a DateTime object representing the current time using the constructor with no argument:
$now = new DateTime();
To get the difference between two dates as a DateInterval object, use the builtin diff method:
$diff = $now->diff($date);
As a complete example:
$now = new DateTime();
$mysqldate = '2018-04-03 12:30:01';
$date = DateTime::createFromFormat('Y-m-d H:i:s', $mysqldate);
$diff = $now->diff($date);
$diff_days = (int)$diff->format('%a');
$diff_hours = $diff->h;
$diff_minutes = $diff->m;
echo "$diff_days days, $diff_hours hours, $diff_minutes minutes";
Output:
125 days, 9 hours, 4 minutes
Note that you have to use $diff->format('%a') rather than $diff->d to get the days between two dates, as $diff->d will not include the days in any months between the two dates (in this example it will return 3 for today being August 6).
Using the DateTime Class in php is the best way to get accurate results.
$dateNow = new DateTime('now');
$dateIn = DateTime::createFromFormat('d-m-Y H:i:s', $timeins[0]);
$interval = $dateNow->diff($dateIn);
echo $interval->format('%d days, %h hours, %i minutes, %s seconds');
$deltaDays = $interval->d;
$deltaHours = $interval->h;
...
You have to make sure the input format for you DB date is correct, in this case, I assumed d-m-y H:i:s, and then you can output in any format you need as well, as shown in the date docs: http://php.net/manual/en/function.date.php

Trying to add 2 dates with DateTime Object PHP

Hi there and thank you for the help. I will try to be breef.
I have a SQL table with one col named "duration" -> type Time
I need to get this "duration" and add to the actual DateTime -> date()
Till now I got something like these:
$id_mission = $_POST["id_mission"];
$sql="SELECT duration FROM missions WHERE id_mission='".$id_mission."'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
How do i pick this: $row['duration'] and convert to DateTime Object?
$date = new DateTime();
$get_datetime = $date->format('Y-m-d H:i:s');
$get_datetime->add(new DateInterval($row['duration']));
I got these sql error:
Fatal error: Call to a member function add() on string in C:\wamp64\www\players\actions\insert_mission.php on line 18
This line converts your DateTime object into a string which you are then trying to call the add() method with. Strings don't have this method.
$get_datetime = $date->format('Y-m-d H:i:s');
To add the date from your row don't use the format method.
$date = new DateTime();
$date->add(new DateInterval($row['duration']));
The error message that you are seeing has nothing to do with SQL, it is telling you that your are trying to treat a string like an object. Which doesn't work in PHP.

Object of class DateTime could not be converted to string in my query. What am I doing wrong here?

I have the following query in php/mysql:
$q2 = $conn3->prepare("SELECT (t.start_time + INTERVAL t.text_duration SECOND) as end_time FROM texts t WHERE t.start_time <= :starttime AND (t.start_time + INTERVAL t.text_duration SECOND) >= :starttime AND t.plot_id = :plot_id LIMIT 1");
$q2->bindValue(':starttime', $start_timestamp);
$q2->bindValue(':plot_id', $plot_id);
$q2->execute();
$check2 = $q2->fetch(PDO::FETCH_ASSOC);
$start_time is a datetime object defined as follows:
$date = new DateTime();
$start_timestamp = $date->add(DateInterval::createFromDateString('10 minutes'));
When I run it, I get the following error:
Catchable fatal error: Object of class DateTime could not be converted to string in ...
How can I fix it?
You only have a DateTime object when you called DateTime::add(). You still have to convert it to a timestamp. Use DateTime::getTimestamp() to do that. You still need to convert it to a datetime value. Use DateTime::format() to do this.
$start_timestamp = $date->add(DateInterval::createFromDateString('10 minutes'))->format('Y-m-d H:i:s');

Categories