Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 707
Jeremy Harris Avatar asked Nov 24 '25 03:11

Jeremy Harris


1 Answers

Use DateTime::format().

like image 85
Matt Ball Avatar answered Nov 26 '25 17:11

Matt Ball