How to compare a datetime to a datetime + X hours with PHP? - php

I got 2 datetimes objects. One is the current datetime. The otherone is when the user Checked in. To which I'd like to add 6 hours.
I first initialize the current datetime:
$now=date("Y-m-d H:i:s");
Then I'm using datediff but I don't now how to add 6 hours, I assume I would have to use modify, but i don't understand how to use it.
$datetimeIn = date_create($result->getDateCheckIn());
$datetimeOut = date_create($now);
date_modify($datetimeOut, '+6 hours');
$interval = date_diff($datetimeIn, $datetimeOut);
if ($interval->format('%a minute') > 0)
$UsersToCheckOut[] = $result;
Can somebody help me figuring howw to add X hours to a datetime to compare it to another ?
I got this error:
date_create() expects parameter 1 to be string, object given in line date_modify($datetimeOut, '+6 hours');
Thanks

I'm going to attempt to answer both your title and the question I inferred you were asking from the body of your question.
The PHP manual is very clear on actually comparing datetimes. Here's example code for that:
$date1 = new DateTime("now");
$date2 = new DateTime("+6 hours");
var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);
//bool(false)
//bool(true)
//bool(false)
The part where you actually add 6 hours is also correct. I copied your code and tested it see if I could get the same error as you. I did when my $datetimeIn parameter was bad. Based off that and the error you posted, it looks very much like the problem lies in your $datetimeIn parameter. I copied my working code below:
$now=date("Y-m-d H:i:s", strtotime('2013-04-15 04:00:0'));
$datetimeIn = date_create($now);
$datetimeOut = date_create($now);
date_modify($datetimeOut, '+6 hours');
$interval = date_diff($datetimeIn, $datetimeOut);
if ($interval->format('%a minute') > 0) {
echo "success";
} else {
echo "fail";
}
According to the error message, it is happening because in your line "$datetimeOut = date_create($now);", the variable $now exists and is some kind of object; date_create() requires the first argument to be some kind of string. See documentation about the valid date and time formats here

You can get a copy, with an offset of 6 hours, like this:
$now = date_create('now');
$future = date_modify(clone $now, '+ 6 hours');
$diff = date_diff($now, $future);
var_dump($diff);die;

$datetimein = date("m/d/Y H:i:s");
$datetimeout = date("m/d/Y H:i:s", strtotime($datetimein) + 6 * 60 * 60);
see it working live: http://codepad.viper-7.com/6wn8dK

Related

How to insert in a wordpress page a widget that shows days since a specific order was made?

I have to output this information but I am not used to work with PHP, don´t know what I am doing wrong.
I query woocommerce order date like this:
$order = wc_get_order(456);
$orderdate = $order->date_created;
That seems to be working ok, it returns a date in this format:
2020-10-15T17:38:37-03:00
For current date, I create a variable like this:
$date = date('d-m-y h:i:s');
But when I try to output the difference in days between order date and current, it always give me 0
This is how I tried to calculate the difference:
function dateDiff($date1, $date2)
{
$date1_ts = strtotime($date);
$date2_ts = strtotime($orderdate);
$diff = $date2_ts - $date1_ts;
return round($diff / 86400);
}
$dateDiff = dateDiff($date1, $date2);
echo ("day difference is: " . $dateDiff );
Thanks a lot for reading, hope you can help me.
Short explanation of what is wrong with your code:
$dateDiff = dateDiff($date1, $date2);
In your case dateDiff is a function which expects two parameters $date1 and $date2. But you are passing non existing variables to the function. They do not exist out of the function scope, because you didn't declare them.
Then you are trying to get timestamps from dates which are in parent scope and probably getting NULL as a result from both cases :)
$date1_ts = strtotime($date);
$date2_ts = strtotime($orderdate);
Small improvements:
Its better to use DateTime class when you are working with dates. DateTime class has powerful method called format that allows you to output date in suitable format for you.
If we combine what you did into one piece of code with some changes, then we will get this:
$order = wc_get_order(456);
$order_date = new DateTime($order->date_created);
$current_date = new DateTime();
function dateDiff($date1, $date2)
{
// check if diff is not equal to zero in order to avoid division be zero exception
if ($diff = abs(strtotime($date2) - strtotime($date1))) {
return round($diff / 86400);
}
return 0;
}
echo ("day difference is: " . dateDiff(
$current_date->format('d-m-Y h:i:s'),
$order_date->format('d-m-Y h:i:s')
) . " days");

PHP datetime comparison is not woking normally

Although my question seems can be found the solution on the internet easily. But I've already tried but it's not working.
I've already followed https://www.php.net/manual/en/datetime.diff.php Example #2 DateTime object comparison
or another solution like https://thevaluable.dev/php-datetime-create-compare-format/ Comparing DateTime Objects
But it is still not working.
Here is my code,
$end_time = new DateTime('2020-04-05 23:59:00');
$now = new DateTime('now');
if( $now > $end_time ){
echo 'expired!';
}
It throws the error
Object of class DateTime could not be converted to string.
Edited
I'm using PHP 7.1.23
Here is the solution for your problem. First you have to convert them into Strings then you can use them. I have changed the input date just to show you the result of if condition.
Select your City for time zone First
date_default_timezone_set('Asia/Karachi');
Your Inputs
$input_time = new DateTime('2020-04-01 23:59:00');
$now = new DateTime('now');
Convert them to string
$input_time = $input_time->format('Y-m-d H:i:s');
$now = $now->format('Y-m-d H:i:s');
The result
if( $now > $input_time )
{
echo 'expired!'. '<br>';
}
If it doesn't need to be an actual DateTime object, you could use times instead, which will then compare the same as an integer would.
Eg
$end_time = strtotime('2020-04-05 23:59:00');
$now = time();
if( $now > $end_time ) {
echo 'expired!';
}

How to retrieve the number of days from a PHP date interval?

I am trying to retrieve the number of days for a PHP interval. When I run the following piece of code on http://sandbox.onlinephpfunctions.com/:
$duration = new \DateInterval('P1Y');
echo $duration->format('%a');
echo "Done";
I get:
(unknown)Done
What am I doing wrong?
The '%a' will return the number of days only when you take a time difference otherwise it will return unknown.
You can use '%d' to get the days but it will also return 0 in the case of new \DateInterval('P1Y') as it does not convert years to days.
One easy way to get the number of days is to create a DateTime at zero time, add the interval to it, and then get the resulting timestamp:
<?php
$duration = new \DateInterval('P1Y');
$intervalInSeconds = (new DateTime())->setTimeStamp(0)->add($duration)->getTimeStamp();
$intervalInDays = $intervalInSeconds/86400;
echo $intervalInDays;
echo " Done";
The problem is here:
$duration->format('%a');
As the manual says, "Total number of days as a result of a DateTime::diff() or (unknown) otherwise".
You need a valid dateInterval object returned by DateTime's diff() method to make the "a" parameter work with DateInterval::format() function:
$now = new DateTime(date('Y-m-d H:i:s'));
$duration = (new DateTime("+1 year"))->diff($now);
echo $duration->format('%a');
Looks like if the DateInterval object is not created by DateTime::diff(), it won't work.
Hope it helps.
You have to create the interval with real dates:
<?php
$interval = date_diff(new DateTime, new DateTime('+1 year'));
echo $interval->format('%a'), PHP_EOL; // 365
if you want something aware of the year or month context, use this, february will return 28 days, leap years will have their additional day
function interval2days($day, $interval) {
$date = clone $day;
$start = $date->getTimeStamp();
$end = $date->add($interval)->getTimeStamp();
return ($end-$start)/86400;
}

Calculate difference between time in DB and Current Time

First off - I am using the MySQLi Procedural method of using MySQL via PHP
I am trying to create a way click a button to set a "timer". From what I understand, the best way to do this (on a dynamic timer - IE: 5 minutes from click) is to calculate what the time() would be 5 minutes from "now".
I want to save this to a DB in case the user disconnects from the page and reconnects (username/password login). This way, when they log back in, it would keep their remaining time.
Now for the code:
I am using this to pull my DT variable from SQL (YYYY-MM-DD HH-MM-SS):
$expirationTime = new DateTime();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$expirationTime = $row['workTimer'];
}
}
$time = strtotime($expirationTime);
$expirationTime = date("Y-m-d H:i:s", $time);
Then I pull the current time:
$currentTime = date('Y-m-d H:i:s');
I have done echos on both of these and they are displaying correctly. What I want to do now is figure out the difference. I have tried multiple ways of doing this, but nothing seems to work. Most recently I did:
$countdown = $currentTime->diff($expirationTime);
$countdown = $countdown->format("Y-m-d H:i:s", $countdown);
with an error of Fatal error: Call to a member function diff() on a non-object in...
What might be the problem?
Thanks!
I have updated some of the codes per the comment's suggestions to:
$currentTimeT = date('Y-m-d H:i:s');
$currentTime = strtotime($currentTimeT);
$time = date("Y-m-d H:i:s", $expirationTime);
$expirationTime = strtotime($expirationTime);
$countdown = $currentTime->diff($expirationTime);
$countdown = $countdown->format("Y-m-d H:i:s", $countdown);
echo "C ".$currentTime."<br/> E ".$expirationTime."<br/>D ".$countdown;
Same Error.
It is likely the least elegant solution but you could cut your to timestrings both into "d,m,y,h,i,s"-substrings and feed them to http://php.net/manual/de/function.mktime.php. Then you calc the difference of the timestamps.
date_diff — Returns the difference between two DateTime objects
and you are passing non-object to function diff()
See this PHP manual
I solved your issues on my side give it a try:
$time = "2016-09-1 04:45:54";
$time = strtotime($time);
$currentTime = new DateTime(date('Y-m-d H:i:s'));
$expirationTime = new DateTime(date("Y-m-d H:i:s",$time));
$countdown = $currentTime->diff($expirationTime);
$countdown1 = $countdown->format("%H:%I:%S");
print_r($countdown1);die;

PHP| arrays with times

I need to compare bentween a time taken from a database to the current time.
$DBtime = "2013-10-29 17:38:55";
this is the format of the arrays in the database.
How can I compare it with the current time?
Im not sure how, but maybe converting DBtime to Unixtime then:
(CurrentUnixTime - dbUnixTime) = x
Or maybe, we can take the 17:38 and compare it somehow with date("G:i");
Thank you! I hope you understand what I mean.
You can transform it into a UNIX timestamp using strtotime and then subtract the current timestamp by it.
$DBtime = "2013-10-29 17:38:55";
$db_timestamp = strtotime($DBtime);
$now = time();
$difference = $now - $db_timestamp;
echo $difference;
This will give you the difference in seconds.
You can convert the DBtime string to a unix timestamp in PHP using strtotime. In MySQL, you can use UNIX_TIMESTAMP when querying the column.
time() - strtotime($DBtime)
$date1 = new DateTime('2013-10-29 17:38:55');
$date2 = new DateTime('2013-11-29 18:28:21');
$diff = $date1->diff($date2);
echo $diff->format('%m month, %d days, %h hours, %i minutes');
$DBtime = "2013-10-29 17:38:55";
// Set whatever timezone was used to save the data originally
date_default_timezone_set('CST6CDT');
// Get the current date/time and format the same as your input date
$curdate=date("Y-m-d H:i:s", time());
if($DBtime == $curdate) {
// They match, do something
} else {
// They don't match
}

Categories