0

I'm having trouble converting a date Time object to a string, so I can pass it through a MySQLi prepared statement which specifies data types.

The error I'm receiving is:

Catchable fatal error: Object of class DateTime could not be converted to string

The line this error refers to is the execution of my prepared statement. I still receive this error despite many attempts at converting the Object to a string. Below I will paste the main 3 ways I've tried to tackle this issue.

1 - Using a casting operator:

$total_hours_calc = $time_diff->format('%h') + ($time_diff->format('%i'))/60;
$total_hours = (string)$total_hours_calc;

2 - Using Print_r:

$total_hours_calc = $time_diff->format('%h') + ($time_diff->format('%i'))/60;
$total_hours = print_r($total_hours_calc, true)

3 - Concatenation workaround:

$total_hours_calc = $time_diff->format('%h') + ($time_diff->format('%i'))/60;
$total_hours = $total_hours_calc . "";

All these attempts return the error stated at the beginning of this question.

Any help, solutions or magic PHP functions unknown to those who have yet to achieve a black belt in the art of PHP - are greatly appreciated.

[Requested] The Prepared statement -

$sql = "INSERT INTO shift ".
       "(uniqueid, shift_date, start_time, end_time, total_hours, rate_of_pay, addedBy, paidRate, totalPaid) ".
       "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)";

$stmt = $connection->prepare($sql);
$stmt->bind_param('sssssssss', $uniqueid, $shift_date, $start_time, $end_time, $total_hours, $rate_of_pay, $addedBy, $paidRate, $totalPaid); 
$stmt->execute();

The line referred to in all errors is: $stmt->execute();

10
  • 1
    What are you trying to do? How do you initialize $time_diff? Commented Apr 24, 2014 at 13:44
  • 1
    show these lines: The line this error refers to is the execution of my prepared statement. Commented Apr 24, 2014 at 13:46
  • $time_diff is simply a date_diff of 2 times. I'm simply trying to convert the dateTime object to a string so it can be stored in database using MySQLi prepared statement. I can't store it as an integer as it can have a decimal point, so I need to store it as a string. Commented Apr 24, 2014 at 13:50
  • @Danieloplata: Can you show us the code you're using? With some example date time strings. Commented Apr 24, 2014 at 13:55
  • as from this: $stmt->bind_param('sssssssss', $uniqueid, $shift_date, $start_time, $end_time, $total_hours, $rate_of_pay, $addedBy, $paidRate, $totalPaid); I assume that there are at least three vars looking like a DateTime Object: $shift_date, $start_time and $end_time. Did you check all of them or how do you know its related to $total_hours? Commented Apr 24, 2014 at 14:05

5 Answers 5

7
+200

According to the php documentation DateTime does not natively implement the __toString() method, which explains the exceptions you keep getting. You may extend DateTime and implement __toString yourself, provided you are using php 5.2 or later.

class DateTimeExt extends DateTime
{
    public function __toString()
    {
        return $this->format("Y-m-d H:i:s");
    }
}

Replace all instances of DateTime used in the bind_param call with DateTimeExt and you should be good.

Sign up to request clarification or add additional context in comments.

Comments

2

I think you're looking in the wrong place by focusing on $total_hours, which is a already a string (or an integer that can be converted to a string)

In the snippet you linked, you're changing the variables $start_time and $end_time from strings to DateTime objects, which would throw the indicated errors when you later try to use them in the prepared statement.
See this snippet, which prints the diff value correctly, but then errors when printing the DateTime object $start_time: https://eval.in/145608

I can think of two possible resolutions:


Use another variable for the string value of $start_time and $end_time in the prepared statement

$start_time = "9:00";
$end_time = "17:30";

$start_time = new DateTime($start_time);
$end_time = new DateTime($end_time);
$time_diff = date_diff($start_time,$end_time);

$start_time_string = $start_time->format('Y-m-d H:i:s');
$end_time_string = $end_time->format('Y-m-d H:i:s');

$stmt->bind_param('sssssssss', $uniqueid, $shift_date, $start_time_string, $end_time_string, $total_hours, $rate_of_pay, $addedBy, $paidRate, $totalPaid); 

Create a subclass of DateTime that implements __toString(), and utilize it instead.

class DateTimeDb extends DateTime {
  public function __toString() {
    return $this->format('Y-m-d H:i:s');
  }
}

$start_time = "9:00";
$end_time = "17:30";

$start_time = new DateTimeDb($start_time);
$end_time = new DateTimeDb($end_time);
$time_diff = date_diff($start_time,$end_time);

$stmt->bind_param('sssssssss', $uniqueid, $shift_date, $start_time, $end_time, $total_hours, $rate_of_pay, $addedBy, $paidRate, $totalPaid); 

1 Comment

Second resolution clears the issue, my apologies for error in the snippet. The $start_time and $end_time variables do not get overwritten in my code, but get assigned to new variables. Not sure why your answer got downvoted, but I will upvote as your answer contains the subclass.
0

you can't add two strings

  $total_hours_calc = intval($time_diff->format('%h'),10) + intval($time_diff->format('%i'),10)/60;

5 Comments

He's not trying to concatenate them. They're just numbers, so it should work just fine.
@Amal again: you can't add two strings. ...format(.. returns a string.
@AxelAmthor: So what? PHP is loosely typed. It works just fine. See this demo.
@Danieloplata: I have tried like below it is returning no of hours. <?php $time_diff = (new DateTime('2014-04-20 03:02:11'))->diff(new DateTime('now')); echo $total_hours_calc = intval($time_diff->format('%h'),10) + intval($time_diff->format('%i'),10)/60; So what is your exact requierement?
The code to return the no. of hours is fine, I'm trying to convert it to a string for storage in database.
0

Parse the values to INT before summing them

$total_hours_calc = (int)$time_diff->format('%h') + ((int)$time_diff->format('%i'))/60;

And quote the result date as string, before using it

$total_hours = "'".$total_hours_calc."'";

There may be a better way to quote the last value.. depending on your implementation,
but $int ."" is usually not enough;

10 Comments

Unfortunately this still returns the error: Catchable fatal error: Object of class DateTime could not be converted to string
on which row? you probably get the error from some other place of the code. can you please paste the exact line from the error ?
The error comes from the line executing the prepared statement - see the updated question.
try to replace $shift_date, $start_time, $end_time, $total_hours with dummy value like '01.01.2014' as string, and see which one is making the problem.
@ramsai there are no errors with the query (it fails before even executed), but one of the assigned variables is an object and not a string as expected.
|
0

You can use format method of the DateTime class :

$date = new DateTime('2014-01-01');
$result = $date->format('Y-m-d H:i:s');

If format fails , it will return FALSE :

if ($result) { // OK
   echo $result;
} 
else { // if format failed
  echo "Unknown Time";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.