67

please help what's wrong with my code? It always returns that today's date is greater than '01/02/2016' wherein 2016 is greater than in 2015.

<?php
$date_now = date("m/d/Y");

$date = date_create("01/02/2016");
$date_convert = date_format($date, "m/d/Y");

if ($date_now > $date_convert) {
    echo 'greater than';
} else {
    echo 'Less than';
}

P.S: 01/02/2016 is coming from the database.

Oscar Gallardo
  • 2,240
  • 3
  • 27
  • 47
Nixxx27
  • 1,021
  • 4
  • 11
  • 13

3 Answers3

181

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • $date_now = new DateTime(); $sql = "UPDATE jrf_tbl SET strifoverdue ='no' WHERE strduedate > '$date_now' "; – Nixxx27 Sep 18 '15 at 01:44
  • strifoverdue is in VARCHAR type. how can i convert it to date and perform my query? TY!! – Nixxx27 Sep 18 '15 at 01:45
  • sorry i mean strduedate is in VARCHAR type meaning im comparing strings and date. i have no idea how to convert strduedate to DATE type in m/d/Y format – Nixxx27 Sep 18 '15 at 01:50
  • What's going on that makes '2016-01-02' a comparable date format? Casting '2016-01-02' to int or float returns 2016. Yet, ( '2016-01-02' < '2016-01-03') is true. – billrichards Jul 13 '18 at 13:02
  • I think this is the explanation. PHP is not casting the string. It's comparing each character in the string https://stackoverflow.com/a/17371819 – billrichards Jul 13 '18 at 13:21
  • @user9437856 I have updated the links to work again. Thank you for pointing it out. – John Conde Feb 14 '19 at 12:37
  • @JohnConde, Yes, this post is old but still working for me. upvote from my side. – user9437856 Feb 14 '19 at 12:43
12

We can convert the dates into timestamps to compare

<?php

    $date_now = time(); //current timestamp
    $date_convert = strtotime('2022-08-01');

    if ($date_now > $date_convert) {
        echo 'greater than';
    } else {
        echo 'Less than';
    }

?>
Joyal
  • 2,587
  • 3
  • 30
  • 45
0

The dates could be in different formats, so it is better to convert them to timestamps before comparison

<?php
 $today = date("Y-m-d"); //Today
 $date = '2022-06-30'; //Date

 if (strtotime($today) > strtotime($date)) {
    echo 'Today is greater than date';
 }else{
    echo 'Today is less than date';
}
Damilare Koiki
  • 341
  • 3
  • 11