php - Ignore time portion when using DateTime::createFromFormat
Get the solution ↓↓↓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 usingDateTime::createFromFormat
and ignore the time portion? I would like to use minimal code to handle both cases.
Answer
Solution:
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.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: php_network_getaddresses: getaddrinfo failed: temporary failure in name resolution
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.