Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore time portion when using DateTime::createFromFormat

Tags:

php

datetime

I have dates coming from database in two formats:

$tests[] = "2018-01-01";
$tests[] = "2018-01-01 12:34:56.789";

Is is possible to convert the strings to DateTime using DateTime::createFromFormat and ignore the time portion? I would like to use minimal code to handle both cases.

like image 753
Salman A Avatar asked Sep 02 '25 13:09

Salman A


1 Answers

You can use the following format:

"!Y-m-d+"

Like so:

echo DateTime::createFromFormat("!Y-m-d+", "2018-01-01")             ->format(DateTime::ATOM); // 2018-01-01T00:00:00+05:00
echo DateTime::createFromFormat("!Y-m-d+", "2018-01-01 12:34:56.789")->format(DateTime::ATOM); // 2018-01-01T00:00:00+05:00
  • ! character resets all date and time components to the left of it to 1970-01-01 00:00:00. Without it, the components not specified in the format are set to components from current time.
  • + character instructs the parser to ignore trailing characters in the date string.
like image 120
Salman A Avatar answered Sep 05 '25 06:09

Salman A