-1

I have the following string with the 'T' seperator - how do change the $format var correctly to take into account the 'T' within the $datestring?

$datestring = '2018-12-30T11:30:00';
$format = 'Y-m-dG:i:s';
$date = DateTime::createFromFormat($format, $datestring);
var_dump($date); // currently returns false rather than an object
Zabs
  • 13,852
  • 45
  • 173
  • 297

1 Answers1

2

You can escape characters in the formats (\T):

$datestring = '2018-12-30T11:30:00';
$date = DateTime::createFromFormat('Y-m-d\TG:i:s', $datestring);

var_dump($date);
// object(DateTime)#1 (3) { ["date"]=> string(26) "2018-12-30 11:30:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" }

If you also need to validate the date you can use DateTime::getLastErrors:

if (!empty(DateTime::getLastErrors()['warning_count'])) {
    echo 'Date <b>' . $datestring . '</b> is invalid.<br>';
}

Because dates like 2018-15-46T29:63:89 would return an object but aren't valid.

AymDev
  • 6,626
  • 4
  • 29
  • 52
  • @Zabs So using this you could forget about the regex you asked about in your previous question and do the validation as part of that creation of the DateTime object – RiggsFolly Aug 22 '18 at 10:23
  • +1 Bit annoyed really. I had a very similiar answer for OP's previous question and it got Dupped just a second before I pressed the Submit Your Answer button :) :) – RiggsFolly Aug 22 '18 at 10:24
  • Might be worth looking at `['error_count']` as well as warnings – RiggsFolly Aug 22 '18 at 10:27
  • @RiggsFolly Oh I hesitated to post this answer on his previous question too. Yep I'm only looking at `['warning_count']` here (but OP could `print_r(DateTime::getLastErrors())` if he wants !) – AymDev Aug 22 '18 at 10:29
  • I thought you may have also seen his previous question :) Great Minds :):) – RiggsFolly Aug 22 '18 at 10:30