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.
Related
i am trying to find difference between two dates in php, the first date is coming from my database (which is in datetime format), so i am converting it to date and then finding the difference using the current date. my code is like below:
$ret=mysqli_query($con,"select * from members");
$cnt=1;
while ($row=mysqli_fetch_array($ret))
{
$date_time = $row['date'];
$new_date = date("Y-m-d",strtotime($date_time));
$dates = date('Y-m-d');
$diff = $new_date->diff($dates);
echo $diff;
}
then i am getting the following error:
Uncaught Error: Call to a member function diff() on string in C:\xampp\htdocs\form\admin\members.php:123 Stack trace: #0 {main} thrown in C:\xampp\htdocs\form\admin\members.php on line 123
can anyone please tell me what i am doing here is wrong. thanks in advance
date function returns a string.
https://www.php.net/manual/en/function.date.php
You can use date_diff function to compare dates in string format
https://www.php.net/manual/en/function.date-diff.php
or use DateTime class which has method diff.
https://www.php.net/manual/en/class.datetime.php
Use date_diff function instead of the object notation here, DateTime object if you want your date to be Object
date() function returns a string. You need to create an object of DateTime class. Your loop should look something like this:
foreach ($ret as $row) {
$new_date = new \DateTime($row['date']);
$diff = $new_date->diff(new \DateTime());
var_dump($diff);
}
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
This problem might be common but it seems like I can't find out what I did wrong.
I have two variables the date and time from database which I think is in UTC format and I need to convert to AEST;
$date = message['date']; //25/09/2014
$time = message['time']; //9:00:00
$combined_time = $date . " " . $time;
$schedule_date = DateTime::createFromFormat("Y-m-d H:i:s",$combined_time ,new DateTimeZone("Australia/Melbourne"));
return $schedule_date->format("jS-A-Y H:i:s T");
I got Call to a member function format() on a non-object exception.
You should use ("d/m/Y h:i:s"):
$schedule_date = DateTime::createFromFormat("d/m/Y h:i:s", $combined_time , new DateTimeZone("Australia/Melbourne"));
The given format is wrong because your date-time is as 25/09/2014 9:00:00. Check this example.
You are not creating any object of class so giving you error you need to create class object or use directly.
$schedule_date = new DateTime($date);
return $schedule_date->format("jS-A-Y H:i:s T");
or you need to pass correct format in Datetime() see #The Alpha answer for this
For more read manual :- http://php.net/manual/en/datetime.createfromformat.php
// convert string to timestamp
$timeStamp = strtotime($combined_time);
// create DateTime object use timestamp
$date = new DateTime();
$date->setTimestamp($timeStamp);
Then you can use $date->format('Y') to get year...
So I'm trying to check if the reset link is expired. Here's what I got
//Get token data
$stmt = $con->prepare("SELECT token_created_at from reset WHERE token = :urltoken");
$stmt->bindValue(':urltoken', htmlspecialchars($_GET['token'], ENT_QUOTES, 'UTF-8'));
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
$token_created_at = $row['token_created_at'];
}
$token_created_at;
//Return current time to match
$current_time = new DateTime();
$my_dt = DateTime::createFromFormat('m-d-Y H:i:s', $token_created_at);
//Modify error
$expires_at = $my_dt->modify('+1 hour');
And how I set the date when the user asks for a reset
//Get creation time
$time_gen = date('m-d-Y H:i:s', time());
Now what happens is I get
Fatal error: Call to a member function modify() on a non-object in /Users/MATT/Desktop/Learn/forgot/activate.php on line 26
Line 26 being
$expires_at = $my_dt->modify('+1 hour');
Any ideas? I've tried other posts, but they don't seem to apply to my issue. They're also stored as VARCHAR
According to the PHP docs:
DateTime::createFromFormat Return Values
Returns a new DateTime instance or FALSE on failure.
So your $my_dt variable is very likely FALSE, which would definitely cause that error.
Your time format string probably needs to be 'Y-m-d H:i:s' if you're using the standard MySQL DATETIME type.
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();