2

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?

4
  • I guess the 'T' at the beginning of the time string is the problem. Does it ever change? What does it do? Commented Jul 11, 2016 at 9:03
  • I think it indicates daylight saving time @KIKOSoftware, actually I don't think that's right. Commented Jul 11, 2016 at 9:04
  • 1
    Yes, the T in the format represents a time zone, not a 'T'. You could try this format: 'Y-m-d \TH:i:s'. The backslash escapes the 'T' to a literal 'T'. Oh, and you really do not need to add in the space. Commented Jul 11, 2016 at 9:09
  • Ah, that works perfectly, I'll pop what I ended up with as answer @KIKOSoftware, cheers for that. Commented Jul 11, 2016 at 9:15

2 Answers 2

2

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.

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

1 Comment

No need to use createFromFormat() with this kind of input; it is perfectly valid input, so just use new DateTime(): demo.
0

Try this

<?php
$d1=$submission['date']='2016-07-11';
$t1=$submission['time']='T09:45:00';
$con=$d1.$t1;
$displaytime=date('d-m-Y H:i:s A',strtotime($con));
echo $displaytime;
?>

It will gives an output like:11-07-2016 09:45:00 AM which you wanted.

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.