phpdatetimeformat

php DateTime no formatting correctly


I have variable of a time (stored in db as CHAR(8), because when stored as TIME throws object error) which I am trying to format and also use to calculate difference with another time.

In this example, the time is stored in DB as "06:00:00", assigned to variable $scheduled_start.

I also have another variable fetched as below.

I then try to create a DateTime object.

$clockIn3 = new DateTime('1970-01-01 ' . $punches[$i]);
$clockIn4 = new DateTime('1970-01-01 ' . $scheduled_start);

I then try to get the difference:

 $interval = $clockIn3->diff($clockIn4);
 echo $interval->format('%H:%I:%S')

And i get correct format:

Difference Mins: 00:04:04

But when I try this, I get completely different result.

$clockIn4->format('%H:%I:%S')

Result:

%06:%0:%st

I also need to check if $clockIn3 and $clockIn4 match, but I can't get what I am doing wrong?


Solution

  • The issue arises from how you're using the format() method. When you call $clockIn4->format('%H:%I:%S'), you are incorrectly using the % symbols, which are not necessary in this case. The DateTime::format() method does not require % for formatting parameters, unlike the DateInterval::format() method, which is what you used to format the difference.

    Remove the % symbols from the format() call when working with DateTime objects.

    Check for equality between two DateTime objects by comparing them directly with the == operator or using the diff() method to see if the difference is zero.

    Try this:

        // Create DateTime objects
    $clockIn3 = new DateTime('1970-01-01 ' . $punches[$i]);
    $clockIn4 = new DateTime('1970-01-01 ' . $scheduled_start);
    
    // Get the difference
    $interval = $clockIn3->diff($clockIn4);
    echo "Difference Mins: " . $interval->format('%H:%I:%S');
    
    // Format the $clockIn4 time
    echo $clockIn4->format('H:i:s');
    
    // Check if $clockIn3 and $clockIn4 match
    if ($clockIn3 == $clockIn4) {
        echo "Times match";
    } else {
        echo "Times do not match";
    }
    

    I hope that helps.