Jeremy Harris
Jeremy Harris

Reputation: 24549

How to Convert DateTime to String?

I have an array of DateTime objects and need to use them as strings in a function call. I have tried casting it like $string_datetime = (string)$myDateTimeObject; but that doesn't work. Searching has been unfruitful as well, as most people are asking how to convert a string to DateTime instead.

My Code:

$start_date = new DateTime();
$end_date = new DateTime();
$end_date = $end_date->modify('+1 day');

// Add time range to request
$request['time_range'] = Array ( 'start' => $start_date,
                                 'end'   => $end_date);

When calling a function which expects a string (it's an API call) I receive this error:

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

What's the correct way of converting/extracting a string from a DateTime object?

Upvotes: 3

Views: 24063

Answers (1)

Matt Ball
Matt Ball

Reputation: 359776

Use DateTime::format().

Upvotes: 6

Related Questions