Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare dates and strings in PHP

i'm developing a PHP program and i must compare a date variable and a string variable. I've tried strcmp but it doesn't work... suggests? Thank's

like image 286
Edoardo Avatar asked Nov 11 '16 12:11

Edoardo


People also ask

How can we compare two dates in PHP?

we can analyze the dates by simple comparison operator if the given dates are in a similar format. <? php $date1 = "2018-11-24"; $date2 = "2019-03-26"; if ($date1 > $date2) echo "$date1 is latest than $date2"; else echo "$date1 is older than $date2"; ?>

Can you use == to compare strings in PHP?

The most common way you will see of comparing two strings is simply by using the == operator if the two strings are equal to each other then it returns true. This code will return that the strings match, but what if the strings were not in the same case it will not match.

How can we compare two strings in PHP?

The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().


1 Answers

Best way of comparing dates is using time-stamps :

$string = '11/05/2016';//string variable
$date = date('Y-m-d',time());//date variable

$time1 = strtotime($string);
$time2 = strtotime($date);
if($time1>$time2){
    //do this
}
else{
    //do this
}

I hope it helps

like image 52
Abhay Maurya Avatar answered Sep 20 '22 19:09

Abhay Maurya