How to compare two dates in php

前端 未结 15 2425
臣服心动
臣服心动 2020-11-22 08:37

How to compare two dates in php if dates are in format \'03_01_12\' and \'31_12_11\' .

I am using this code:

$date1=date(\'         


        
相关标签:
15条回答
  • 2020-11-22 09:22

    Guys Please don't make it so complex The simple answer bellow

    $date1=date('d_m_y');
    $date2='31_12_11';
    $date1=str_replace('_', '-', $date1);
    $date2=str_replace('_', '-', $date2)
    if(strtotime($date1) < strtotime($date2))
       echo '1 is small ='.strtotime($date1).','.$date1;
    else
       echo '2 is small ='.strtotime($date2).','.$date2;
    

    I just have added two more lines with your code

    0 讨论(0)
  • 2020-11-22 09:24

    You will have to make sure that your dates are valid date objects.

    Try this:

    $date1=date('d/m/y');
    $tempArr=explode('_', '31_12_11');
    $date2 = date("d/m/y", mktime(0, 0, 0, $tempArr[1], $tempArr[0], $tempArr[2]));
    

    You can then perform the strtotime() method to get the difference.

    0 讨论(0)
  • 2020-11-22 09:24

    Using DateTime::createFromFormat:

    $format = "d_m_y";
    $date1  = \DateTime::createFromFormat($format, "03_01_12");
    $date2  = \DateTime::createFromFormat($format, "31_12_11");
    
    var_dump($date1 > $date2);
    
    0 讨论(0)
  • 2020-11-22 09:24

    The date_diff() function returns the difference between two DateTime objects.

    If the first date is before the second date a positive number of days will be returned; otherwise a negative number of days:

    <?php
    $date1=date_create("2013-03-15");
    $date2=date_create("2013-12-12");
    $diff=date_diff($date1,$date2);
    echo $diff->format("%R%a days");
    ?>
    

    output will be "+272 days" ;

    changing $date1 = "2014-03-15"

     <?php
        $date1=date_create("2014-03-15");
        $date2=date_create("2013-12-12");
        $diff=date_diff($date1,$date2);
        echo $diff->format("%R%a days");
        ?>
    

    Output will be "-93 days"

    0 讨论(0)
  • 2020-11-22 09:25

    I think this one is very simple function

    function terminateOrNotStringtoDate($currentDate, $terminationdate)
    {
        $crtDate = new DateTime($currentDate);
        $termDate = new DateTime($terminationdate);
        if($crtDate >= $termDate)
        {
            return true;
        } else {
        return false;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 09:28

    Extending @nevermind's answer, one can use DateTime::createFromFormat: like,

    // use - instead of _. replace _ by - if needed.
    $format = "d-m-y";
    $date1  = DateTime::createFromFormat($format, date('d-m-y'));
    $date2  = DateTime::createFromFormat($format, str_replace("_", "-",$date2));    
    var_dump($date1 > $date2);
    
    0 讨论(0)
提交回复
热议问题