7

In my PHP application I'm trying to compare date time values like the following:

if($datetime_from_db < date('Y-m-d H:i:s'))
{
    // then do something
}

Both values are in the same format. What I can't figure out is why it only compares the date and ignores the time. Both the date and the time values are important for me but I don't know how to make it work.

4 Answers 4

22

Comparing a string like "2011-02-14 15:46:00" to another string doesn't actually compare dates, it compares two strings according string parsing numeric rules. You will need to compare actual numeric timestamps:

strtotime($datetime_from_db) < time()
Sign up to request clarification or add additional context in comments.

2 Comments

So I can do: strtotime($datetime_from_db) < strtotime(date('Y-m-d H:i:s')) ? Will that work?
@dtn Yes, but strtotime(date('Y-m-d H:i:s')) is the same as time().
9

If you want this to work with dates past 2038, you can't use strtotime() or time().

See this question for the explanation.

A better approach:

new DateTime($datetime_from_db) < new DateTime();

Comments

0

This may help you.

$today = date("m-d-Y H:i:s");
$thisMonth =date("m");
$thisYear = date("y");
$expectedDate = $thisMonth."-08-$thisYear 23:58:00";
//pr($today);
//pr($expectedDate);


    if (strtotime($expectedDate) > strtotime($today)) {
        echo "Expected date is greater then current date";
        return ;
    } else
        {
         echo "Expected date is lesser then current date";
        }

Comments

0

Here is a solution where we use strtotime. I give two examples. First one comparing the whole timestamp. Second one is just compare the date.

<?php
$date = "2022-10-06 17:49:10"; // string. can set any current timestamp

#example 1 - compare the date and time Y-m-d H:i:s
if(date("Y-m-d H:i:s" , strtotime($date)) >= date("Y-m-d H:i:s")){
    echo "the date checked is bigger than today";
}else{
    echo "the date checked is smaller than today";
}

#example 2 - compare the date only Y-m-d 
if(date("Y-m-d" , strtotime($date)) == date("Y-m-d")){
    echo "same day is true";
}else{
    echo "same day is false";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.