PHP 函数返回两个unix时间戳之间的时间量,因为它将被语言化。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 函数返回两个unix时间戳之间的时间量,因为它将被语言化。相关的知识,希望对你有一定的参考价值。

function timeSince($start,$end='',$units=2) { // $start and $end should be Unix time() format

    // Common time periods as an array of arrays
    $periods = array(
        array(60 * 60 * 24 * 365 , 'year'),
        array(60 * 60 * 24 * 30 , 'month'),
        array(60 * 60 * 24 * 7, 'week'),
        array(60 * 60 * 24 , 'day'),
        array(60 * 60 , 'hour'),
        array(60 , 'minute'),
        array(1 , 'second'),
    );
   
    $end = (!empty($end))?$end:time(); // if no end timestamp given use the current one for end date
    $since = $end - $start; // Find the difference of time between now and the past
                            // $end and $start input could be swapped in order to find the time 'until' ;)
    // Loop around the periods, starting with the biggest
    for ($i = 0, $j = count($periods); $i < $j; $i++){    
        $seconds = $periods[$i][0];
        $name = $periods[$i][1];
       
        // Find the biggest whole period
        if (($count = floor($since / $seconds)) != 0){
            break;
        }
    }
   
    $output = ($count == 1) ? '1 '.$name : "$count {$name}s";
    $deducted = ($seconds * $count);

    for($z = 1, $j = count($periods); $z < $j; $z++) {
      if ($units > $z && $i + $z < $j){
          // Retrieving the next requested relevant period
          $seconds = $periods[$i + $z][0];
          $name = $periods[$i + $z][1];
         
          // Only show it if it's greater than 0
          if (($count = floor(($since - $deducted) / $seconds)) != 0){
              $deducted = $deducted+($seconds * $count);
              $output .= ($count == 1) ? ', 1 '.$name : ", {$count} {$name}s";
          }
      }
    }

    return $output;
}

以上是关于PHP 函数返回两个unix时间戳之间的时间量,因为它将被语言化。的主要内容,如果未能解决你的问题,请参考以下文章

查找 Unix 时间戳之间的最新间隔

php time()函数 语法

通过 PHP mktime() 创建日期

php日期转时间戳

计算两个时间戳之间的差异并获得 unix 时间戳的差异

在php中查找2个unix时间戳之间的天数