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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With