PHP:find day difference between two date(“YmdHis”) reture

后端 未结 4 2069
无人及你
无人及你 2020-12-11 11:08

I need to find the day difference from the date(\"YmdHis\") value.let say one value is:

$previous_date=\'20101202115755\';
$current_date= date(\         


        
相关标签:
4条回答
  • 2020-12-11 11:42

    You have a strange format...

    1. Parse it to get a UNIX timestamp with strptime and mktime:

      $d = strptime($previous_date, '%Y%m%d%H%M%S');
      $prev_ts = mktime($d['tm_hour'], $d['tm_min'], $d['tm_sec'], $d['tm_mon'] + 1, $d['tm_mday'], $d['tm_year'] + 1900);
      
    2. Subtract the timestampes (time() gives the current time):

      $diff = time() - $prev_ts;
      
    3. Divide by 60*60*24 seconds to get the difference in days:

      $diff = floor($diff / (60*60*24)); // or round(), ceil() whatever fits best
      

    That said, if possible try to store or get the date not as 20101202115755 but as UNIX timestamp. Then you don't have to go through the conversion hassle.

    Working DEMO

    0 讨论(0)
  • 2020-12-11 11:47

    For PHP >= 5.3.0:

    $prev = DateTime::createFromFormat("YmdHis", '20101202115755');
    $curr = new DateTime();
    $diff = $curr->diff($prev);
    echo "Difference: ".$diff->days;
    
    0 讨论(0)
  • 2020-12-11 11:54

    Just convert your dates to timestamps and then subtract previous_date from current_date and divide by number of seconds in a day. This is an example:

    $day = 60*60*24;
    
    $now = time();
    $target = strtotime('2010-12-24');
    
    $diff = round(($target - $now) / $day);
    echo $diff;
    

    If you want number of days in between, subtract $diff by one.

    0 讨论(0)
  • 2020-12-11 11:58
    <?php
    $previous_date="201012021157552";
    $previous_date_as_time = mktime(
      substr($previous_date, 8, 2),
      substr($previous_date, 10, 2),
      substr($previous_date, 12, 2),
      substr($previous_date, 4, 2),
      substr($previous_date, 6, 2),
      substr($previous_date, 0, 4)
    );
    
    $days_between_dates = (time() - $previous_date_as_time) / 86400;
    
    echo $days_between_dates;
    ?>
    
    0 讨论(0)
提交回复
热议问题