Date diffrent function showing error in my live server - php

here is the code of my block it gives error
$inti_date=strtotime($row->inti_date);
$inti_date=date('Y-m-d',$inti_date);
$diff=date_diff($today,$inti_date);
$temp = $diff->format("%a");

I assume you are dealing with a date from your database and want to remove the time portion from a DateTime column.
If you notice the prototype for date_diff
DateInterval date_diff ( DateTimeInterface $datetime1 , DateTimeInterface $datetime2 [, bool $absolute = false ] )
date_diff requires the dates to be of type DateTimeInterface therefore the dates need to be created using the DateTime Class
// fake an object just for testing
$row = new stdClass();
$row->inti_date = '2017-05-01 10:10:10';
$inti_date = new DateTime($row->inti_date);
// I assume you were just after the data portion in both cases
// So set time to 0 o'clock
$inti_date->setTime(0,0,0);
$today = new DateTime('now');
// set time to 0 o'clock
$today->setTime(0,0,0);
$diff = date_diff($today,$inti_date);
$temp = $diff->format("%a");
echo $temp;
// or you could code the diff processing like this
$diff = $today->diff($inti_date);
echo $diff->format("%a");
Result on 04/05/2017 is
3

Related

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

Not getting the required date

I want to calculate the difference between date using date_diff(), whose 1st parameter is saved data in database and the 2nd parameter is today's date. The $pro_deadline is coming from database and is of type text (format yyyy-mm-dd), so I converted it into time using strtotime(). But in the end I'm getting "
Warning
: date_diff() expects parameter 1 to be DateTimeInterface, string given"
$today = date("Y-m-d");
echo $today;
$end = strtotime($pro_deadline);
$end_line = date("Y-m-d",$end);
echo $end_line;
$diff = date_diff($end_line,$today);
echo $diff;
as per PHP documentation http://php.net/manual/en/function.date-diff.php
date_diff — Alias of DateTime::diff()
so the perameters to date_diff should be DateTimeInterface types.
i would try
<?php
$today = date("Y-m-d");
echo $today." ";
$today = date_create($today);
$pro_deadline = '10-15-18';
$end = strtotime($pro_deadline);
$end_line = date_create(date("Y-m-d",$end));
$diff = date_diff($end_line,$today);
echo $diff->format('%a');
echo " days apart";
?>
the date_create() function is an alias of the DateTime constructor.
http://php.net/manual/en/datetime.construct.php
this creates an interface for the date/time that the date_diff() function can interpret. then date_diff() returns a DateInterval object
http://php.net/manual/en/class.dateinterval.php
the DateInterval object has a format method
http://php.net/manual/en/dateinterval.format.php
that can return the date in a sting for you.
Hope this explanation helps!
Like the error message says, date_diff expects DateTimeInterface parameters. strtotime returns a timestamp as an integer, which it can't work with.
Instead of creating timestamps, you can pass your deadline to the DateTime constructor, along with another version that'll default to now:
$today = new DateTime;
$end = new DateTime($pro_deadline);
and then pass these two objects to date_diff, and use the DateInterval::format method to display the number of days (assuming this is your desired output):
$diff = date_diff($today,$end);
echo $diff->format('%a');
See https://3v4l.org/QVkad for a full example
First of all, if you want a difference between a date in a database and today's date, just do it in the database directly. You didn't specify which DB, but, for example in MySQL you'd do something like:
SELECT DATEDIFF(some_field, now()) FROM ...
If you insist on doing it in PHP, then don't use strtotime but use DateTime object:
$today = new DateTime();
$end = new DateTime($pro_deadline);
$diff = $end.diff($today)
The date() function returns a simple string, but the date_diff() function expects a date object.
You can do it all much more simply with the functions in the DateTime class:
$pro_deadline = "2018-09-01";
$today = new DateTime();
$end = new DateTime($pro_deadline);
$interval = $end->diff($today);
echo $interval->format('%R%a days');
This example outputs +25 days Click here for Runnable Demo
Further examples of the diff() function here

PHP Time Difference - diff [duplicate]

This question already has answers here:
How to calculate the difference of datetime field and now in PHP?
(3 answers)
Closed 9 years ago.
I have utilised some code already found on another question.
<?
$start_date = new DateTime('now');
$timestamp = strtotime( $nt['last_seen'] );
$since_start = $start_date->diff($timestamp);
echo $since_start->i.' minutes<br>';
echo $since_start->s.' seconds<br>';
?>
This does not seem to work ?? the timestamp is pulled in from mysql statement in the format.
yyyy-mm-dd hh:mm:ss
The first parameter in diff() method expects a DateTime object, but you're supplying a Unix timestamp instead.
Use the following code instead:
$start_date = new DateTime('now');
$end_date = new DateTime($nt['last_seen']);
$since_start = $start_date->diff($end_date);
echo $since_start->format('%i').' minutes<br>';
echo $since_start->format('%s').' seconds<br>';
Demo!
As Glavić notes in the comment below, it's possible to create a DateTime object from a Unix timestamp, too:
$date = new DateTime("#$timestamp"); // $timestamp is astring -- eg: 1382025097
But it is not necessary in this case, and the first method should work just fine.
$start_date = new DateTime('now');
$timestamp = new DateTime($nt['last_seen']);
$since_start = $start_date->diff($timestamp);
echo $since_start->format('%m').' minutes<br>';
echo $since_start->format('%s').' seconds<br>';
you need to cast your $timestamp as a new DateTime something like the above
I have a couple of wrapper functions I use look at the db date diff one sql query if you're pulling your $timestamp from the database then there's no reason you can't do the diff in your master query and completely remove the need to do it in PHP after.
/**
* Date Diff between now and submitted data
* #param - $date - takes current date
* #return int number of days between inputted dates +ve numbers are start date in past -ve numbers are end date in future of now()
*/
function daves_date_diff($date) {
$start = new DateTime($date);
$today = new DateTime();
$diff = $start->diff($today);
return $diff->format('%d');
}
/**
* Database select based date diff as its more reliable than using php date diffs
* #param - $date - date string in mysql format of date to diff against
* #return - int - number of days date is different from now
*/
function db_date_diff($date) {
global $db;
$date = mysqli_real_escape_string($db->mysqli,$date);
$returneddiff = $db->queryUniqueObject("SELECT DATEDIFF('$date',NOW()) as DateDiff",ENABLE_DEBUG);
return $returneddiff->DateDiff;
}

Doctrine2 subtract two datetimes

So in my database I got a datetime field, filled with e.g. 2012-09-19 11:20:33.
Now I'm trying to fetch the datetime.
$blabla = $something->getDatetime();
After that I create a new DateTime, which represents the time now
$now = new \DateTime("now");
And after that I want to subtract them like this (but it doesn't work)?
$test1 = strtotime($blabla);
$test2 = strtotime($now);
$diff = $test2 - $test1;
echo $diff;
My aim is to subtract the persisted datetime in the database from the time now...the result should be displayed in seconds...so 2012-09-19 11:22:22 - 2012-09-19 11:20:22 equals 120 (seconds).
I also tried to persist a unix timestamp into my database but unfortunately the field type timestamp doesn't exist.
If you want the answer displayed in seconds, then just subtract the timestamps:-
$blabla = $something->getDatetime();
$now = new DateTime();
$seconds = $now->getTimestamp() - $blabla->getTimestamp();
$blabla = $something->getDatetime();
$now = new \DateTime("now");
$diff = $now->diff($blabla);
Remember that $diff is a DateInterval object en you must use its methods and properties to get to the final desired result.

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