PHP datetime comparison is not woking normally - php

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!';
}

Related

Date difference in PHP code does not execute

I have a code in PHP 5.5.11 where I am trying to do the following:
Get today's date in a variable --> $today
Calculate the end of month from a date in a form --> $st_dt_eom
if difference between these 2 dates is more than 5 days then execute a code. The code in the if condition below does not execute.
$today= date();
if($_POST['Submit']=='SAVE')
{
$st_dt=YYYYMMDD($_POST['st_dt'],"-");
$st_dt_eom= datetime::createfromformat('YYYYMMDD',$st_dt);;
$st_dt_eom->modify('last day of this month');
$diff = $today->diff($st_dt_eom);
$diffDays= intval($diff->format("%d")); //to get integer number of days
if($diffDays>5){
redirect("index.php");
}
}
An example:
// 2022-12-19
$today = date('Y-m-d');
// $_POST['st_dt']
$st_dt = '2022-12-31';
function dateDiffDays($today, $st_dt)
{
$today_obj= DateTime::createfromformat('Y-m-d', $today);
$st_dt_eom= DateTime::createfromformat('Y-m-d', $st_dt);
$diff = $today_obj->diff($st_dt_eom);
return $diff->days;
}
// int(12)
$res = dateDiffDays($today, $st_dt);
use var_dump to locate your bug.
A few suggestions to improve your code and produce something workable:
<?php
// Instead of using date(), use a DateTime() then you're comparing two DateTimes later on
$today = new DateTime();
// I'm assuming that your YYYYMMDD function removes "-" from the $_POST['st_dt']
// to provide a date in the format YYYYMMDD (or Ymd in PHP).
// Unfortunately, DateTime doesn't understand that format.
// So I'd change this for keeping Y-m-d (YYYY-MM-DD).
// Or modify your code to return that format!
$st_dt = $_POST['st_dt'];
// Watch out for your cAsE when using PHP functions!
$st_dt_eom = DateTime::createFromFormat('Y-m-d',$st_dt);
$st_dt_eom->modify('last day of this month');
$diff = $today->diff($st_dt_eom);
$diffDays= intval($diff->format("%d"));
if($diffDays > 5){
redirect("index.php");
}

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");

How to compare a datetime to a datetime + X hours with 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

php check if specified time has expired

I am trying to compare the current datetime, with a datetime from the database using string, as the following:
$today = new DateTime("now");
$todayString = $today->format('Y-m-d H:i:s');
if($todayString >= $rows["PrioritizationDueDate"])
{...}
$todayString keeps giving me the time 7 hours earlier (i.e now its 11:03pm, its giving me 16:04).
More, is it better to compare this way, or should i compare using datetime objects?
$todayString keeps giving me the time 7 hours earlier
you have to setup a timezone for the DateTime object I believe.
is it better to compare this way
I doubt so.
The general way is to compare in the query, using SQL to do all date calculations and return only matching rows.
Set a correct timezone in the constructor to DateTime.
$today = new DateTime("now", new DateTimeZone('TimezoneString'));
Where TimezoneString is a valid timezone string.
Edit: For a more complete example using DateTime objects, I would use DateTime::diff in conjunction with DateTime::createFromFormat.
$rows["PrioritizationDueDate"] = '2011-11-20 10:30:00';
$today = new DateTime("now", new DateTimeZone('America/New_York'));
$row_date = DateTime::createFromFormat( 'Y-m-d H:i:s', $rows["PrioritizationDueDate"], new DateTimeZone('America/New_York'));
if( $row_date->diff( $today)->format('%a') > 1)
{
echo 'The row timestamp is more than one day in the past from now.';
}
Demo
First set time zone using this function
date_default_timezone_set('UTC');
Then either you can use function strtotime() or get difference directly...

How to get millisecond between two dateTime obj?

How to get millisecond between two DateTime objects?
$date = new DateTime();
$date2 = new DateTime("1990-08-07 08:44");
I tried to follow the comment below, but I got an error.
$stime = new DateTime($startTime->format("d-m-Y H:i:s"));
$etime = new DateTime($endTime->format("d-m-Y H:i:s"));
$millisec = $etime->getTimestamp() - $stime->getTimestamp();`
I get the error
Call to undefined method DateTime::getTimestamp()
In the strict sense, you can't.
It's because the smallest unit of time for the DateTime class is a second.
If you need a measurement containing milliseconds then use microtime()
Edit:
On the other hand if you simply want to get the interval in milliseconds between two ISO-8601 datetimes then one possible solution would be
function millisecsBetween($dateOne, $dateTwo, $abs = true) {
$func = $abs ? 'abs' : 'intval';
return $func(strtotime($dateOne) - strtotime($dateTwo)) * 1000;
}
Beware that by default the above function returns absolute difference. If you want to know whether the first date is earlier or not then set the third argument to false.
// Outputs 60000
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31");
// Outputs -60000 indicating that the first argument is an earlier date
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31", false);
On systems where the size of time datatype is 32 bits, such as Windows7 or earlier, millisecsBetween is only good for dates between 1970-01-01 00:00:00 and 2038-01-19 03:14:07 (see Year 2038 problem).
Sorry to digg out an old question, but I've found a way to get the milliseconds timestamp out of a DateTime object:
function dateTimeToMilliseconds(\DateTime $dateTime)
{
$secs = $dateTime->getTimestamp(); // Gets the seconds
$millisecs = $secs*1000; // Converted to milliseconds
$millisecs += $dateTime->format("u")/1000; // Microseconds converted to seconds
return $millisecs;
}
It requires however that your DateTime object contains the microseconds (u in the format):
$date_str = "20:46:00.588";
$date = DateTime::createFromFormat("H:i:s.u", $date_str);
This is working only since PHP 5.2 hence the microseconds support to DateTime has been added then.
With this function, your code would become the following :
$date_str = "1990-08-07 20:46:00.588";
$date1 = DateTime::createFromFormat("Y-m-d H:i:s.u", $date_str);
$msNow = (int)microtime(true)*1000;
echo $msNow - dateTimeToMilliseconds($date1);
DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the 'u' format string.
<?php
// Instantiate a DateTime with microseconds.
$d = new DateTime('2011-01-01T15:03:01.012345Z');
// Output the microseconds.
echo $d->format('u'); // 012345
// Output the date with microseconds.
echo $d->format('Y-m-d\TH:i:s.u'); // 2011-01-01T15:03:01.012345
// Unix Format
echo "<br>d2: ". $d->format('U.u');
function get_data_unix_ms($data){
$d = new DateTime($data);
$new_data = $d->format('U.u');
return $new_data;
}
function get_date_diff_ms($date1, $date2)
{
$d1 = new DateTime($date1);
$new_d1 = $d1->format('U.u');
$d2 = new DateTime($date2);
$new_d2 = $d2->format('U.u');
$diff = abs($new_d1 - $new_d2);
return $diff;
}
https://www.php.net/manual/en/class.datetime.php
Here's a function to do that + tests.
https://gist.github.com/vudaltsov/0bb623b9e2817d6ce359eb88cfbf229d
DateTime dates are only stored as whole seconds. If you still need the number of milliseconds between two DateTime dates, then you can use getTimestamp() to get each time in seconds (then get the difference and turn it into milliseconds):
$seconds_diff = $date2.getTimestamp() - $date.getTimestamp()
$milliseconds_diff = $seconds_diff * 1000

Categories