Jack hardcastle Jack hardcastle - 4 months ago 17
PHP Question

Create DateTime from date string and time string

I have a form that submits both a date and a time, and I wish to create one \DateTime object based on these values

The

$submission['time']
value looks like: 'T09:45:00'

The
$submission['date']
value looks like: '2016-07-11'

I've tried

var_dump(\DateTime::createFromFormat(
'Y-m-d TH:i:s', $reportArray['date'] . ' ' . $reportArray['time'])
); // also tried without 'T' (TH:i:s)


However this broke the script.

Is there a simple way to create one \DateTime object from one date string and one time string?

Answer

The 'T' you have used in the format represents a time zone, not a literal 'T'. You could use this format: 'Y-m-d\TH:i:s'. The backslash escapes the 'T' to a literal 'T'. I left out the space, because you don't need it. Like this:

var_dump(\DateTime::createFromFormat(
    'Y-m-d\TH:i:s', $reportArray['date'] . $reportArray['time'])
); 

This answer does, of course, assume that the 'T' is always there and never changes.