Skip to content
Advertisement

How to know if a date/time string contain day or not in php?

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?

Advertisement

Answer

I think you are expecting some thing like this.

<?php
$date1 = "2021-02";
$date2 = "2021-02-11";
$date3 = "2021-12";
$date4 = "2021-12-14";
$date1_array = explode("-", $date1);
$date2_array = explode("-", $date2);
$date3_array = explode("-", $date3);
$date4_array = explode("-", $date4);

if (count ($date1_array) == 3)
{
    echo $date1 . ": It's a Date.";
    echo "<br />";
}
if (count ($date2_array) == 3)
{
    echo $date2 . ": It's a Date.";
    echo "<br />";
}
if (count ($date3_array) == 3)
{
    echo $date3 . ": It's a Date.";
    echo "<br />";
}
if (count ($date4_array) == 3)
{
    echo $date4 . ": It's a Date.";
    echo "<br />";
}

?>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement