Error in PHP $date2 = $date1->format('Y-m-d') - php

I get the following error:
PHP Fatal error: Call to a member function format() on a non-object
in code:
$date = new DateTime();
$date1 = $date->modify('-6 months');
$date2 = $date1->format('Y-m-d');
I want to get this date of 6 months before from now and delete all entries in database which are earlier than this 6 months date:
$query = $conn->prepare("DELETE FROM files WHERE files.date < ?");
$query->bind_param('s', $date2);
$query->execute();
In MySQL "date" field is in files table of datatype "timestamp" whose value is "CURRENT_TIMESTAMP" stored by MySQL as default when a row is created.

This code get you 6 month ago from now:
date('Y-m-d', strtotime('now -6 month'))
EDIT:
and use DateTime:
echo (new DateTime('-6 months'))->format('Y-m-d');

try below code:
<?php
$date = new DateTime('-6 months');
echo $date2 = $date->format('Y-m-d');
?>

It appears you are using an outdated version of php.
Starting with php 5.3+ DateTime::modify returns the datetime object is was called upon prior to that null was returned.
You don't need to assign the result of modify to a new variable as it modifies the current object and does not return a new one.
To make it work on 5.2:
<?php
$date = new DateTime();
$date->modify('-6 months');
$dateS = $date->format('Y-m-d');
var_dump($dateS);
You should however update your php to a supported version.
PHP 5.4+ short-example:
$dateS = (new DateTime('-6 months'))->format('Y-m-d');

Seems like the call to
$date->modify('-6 months');
encounters an error and does not return a DateTime instance but probably false (see documentation).
Which PHP version are you using? I could not reproduce that error with the given example on PHP 5.5.9
Maybe you could just use the strtotime function
EDIT:
I took the Wayback Machine from Internet Archive and found that older versions of PHP ( i.e. 5.1.0) returned NULL instead of the DateTime object: see for yourself. In that case it seems like you apply the modification on your date directly so you need to change your code to
$date = new DateTime();
$date->modify('-6 months');
$dateString = $date->format('Y-m-d');
$query = $conn->prepare("DELETE FROM files WHERE files.date < ?");
$query->bind_param('s', $dateString);
$query->execute();

Related

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

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.

php datetime using existing date to create new date with added days

I have a date:
$launched=new DateTime();
I would like to create a new DateTime using $launched but adding days. Something like:
$expired=new DateTime($launched->modify("+$expiry days"));
How can I do this?
Assuming you are using PHP 5.5 or newer DateTimeImmutable makes this easy:
$launched = new DateTimeImmutable();
$expired = $launched->modify("+$expiry days");
DateTimeImmutable does not modify the original object which is what DateTime does. So you can just assign the resulting object return by modify() to a variable and have a new object with a date in the future.
If you are using an older, and obsolete, version of PHP you can clone the original object to achieve the same result:
$launched = new DateTimeImmutable();
$expired = clone $launched;
$expired->modify("+$expiry days");

$date = new DateTime for older PHP versions

Using the code below I received an error and I found out that it has to do with my server not having the latest PHP running:
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('PT'.$a->metrics->duration.'S'));
The Error:
Fatal error: Call to undefined method DateTime::add()
The Question:
How would I achieve the above for a server that is running PHP 5.2.17 ?
You can make use of strtotime():
$date = strtotime ("2000-01-01");
$date = strtotime ("+900 seconds", $date); // adds 900 seconds to date
$start = new DateTime() ;
$start->modify( '+900 seconds' ) ;
var_dump( $start->format('h:i:s' ));
Using modify should still work for your version, enabling you to stick with DateTime, works for me on 5.2.6

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...

Categories