I want to check if a date/time string contains a day or not.
I used the date_parse()
function but it automatically adds day => 1 if it doesn't find any day.
So I couldn't know if a string contains a day or not.
For example
$date = "2021-02";
How to know if this string contains a day or not?
My Answer:
You can use the `DateTime::createFromFormat()` function in PHP to check if a date/time string contains a day or not. Here is an example code snippet:
php
$dateString = "2022-01-01 12:00:00";
$date = DateTime::createFromFormat('Y-m-d H:i:s', $dateString);
if ($date && $date->format('d') != '00') {
echo "Date string contains a day.";
} else {
echo "Date string does not contain a day.";
}
In this code snippet, we are creating a `DateTime` object from the date/time string using the `createFromFormat()` function. We then check if the day part of the date is not equal to '00' (which would indicate that the day is missing). If the day is present, it will output "Date string contains a day", otherwise it will output "Date string does not contain a day".
Rate this post
5 of 5 based on 6421 votesComments