Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Compare datetime values

Tags:

php

datetime

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.

like image 879
dtntcdr Avatar asked Feb 14 '11 06:02

dtntcdr


People also ask

Can I compare date in PHP?

You can PHP date compare with current date by using the strtotime() function along with comparison operators. The date_diff() function allows you to compare two dates and find the difference between them.

How can I compare today's date with another date in PHP?

Once you have created your DateTime objects, you can also call the diff() method on one object and pass it the other date in order to calculate the difference between the dates. This will give you back a DateInterval object. $last = new DateTime( "25 Dec 2020" ); $now = new DateTime( "now" );

How can I compare two time in PHP?

php $start = strtotime("12:00"); $end = // Run query to get datetime value from db $elapsed = $end - $start; echo date("H:i", $elapsed); ?>


1 Answers

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()
like image 99
deceze Avatar answered Oct 03 '22 05:10

deceze