【问题标题】:PHP How to find the time elapsed since a date time? [duplicate]PHP如何查找自日期时间以来经过的时间? [复制]
【发布时间】:2011-02-24 08:15:14
【问题描述】:

如何查找自 2010-04-28 17:25:43 之类的日期时间戳以来经过的时间,最终输出文本应类似于 xx Minutes Ago/xx Days Ago

【问题讨论】:

  • 这与 PHP 无关,与 Java 或 Javascript 无关
  • 今天的 unix 时间戳减去你的日期时间作为 unix 时间戳,然后将结果除以 86400 秒以获得以天为单位的时间

标签: php date time timestamp relative-time-span


【解决方案1】:

为了改进 @arnorhs 的回答,我添加了获得更精确结果的能力,因此如果您想要几年、几个月、几天和几小时,例如用户加入后。

我添加了一个新参数,允许您指定希望返回的精度点数。

function get_friendly_time_ago($distant_timestamp, $max_units = 3) {
    $i = 0;
    $time = time() - $distant_timestamp; // to get the time since that moment
    $tokens = [
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    ];

    $responses = [];
    while ($i < $max_units && $time > 0) {
        foreach ($tokens as $unit => $text) {
            if ($time < $unit) {
                continue;
            }
            $i++;
            $numberOfUnits = floor($time / $unit);

            $responses[] = $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '');
            $time -= ($unit * $numberOfUnits);
            break;
        }
    }

    if (!empty($responses)) {
        return implode(', ', $responses) . ' ago';
    }

    return 'Just now';
}

【讨论】:

  • 代码运行良好。谢谢
【解决方案2】:

请注意,大多数数学计算示例的硬性限制为 2038-01-18 日期,不适用于虚构日期。

由于缺少基于 DateTimeDateInterval 的示例,我想提供一个多功能函数来满足 OP 的需求和其他想要复合经过时间段的人,例如 1 month 2 days ago。连同一堆其他用例,例如显示日期而不是经过时间的限制,或者过滤掉经过时间结果的部分。

此外,大多数示例都假设过去时间是从当前时间开始的,下面的函数允许用所需的结束日期覆盖它。

/**
 * multi-purpose function to calculate the time elapsed between $start and optional $end
 * @param string|null $start the date string to start calculation
 * @param string|null $end the date string to end calculation
 * @param string $suffix the suffix string to include in the calculated string
 * @param string $format the format of the resulting date if limit is reached or no periods were found
 * @param string $separator the separator between periods to use when filter is not true
 * @param null|string $limit date string to stop calculations on and display the date if reached - ex: 1 month
 * @param bool|array $filter false to display all periods, true to display first period matching the minimum, or array of periods to display ['year', 'month']
 * @param int $minimum the minimum value needed to include a period
 * @return string
 */
function elapsedTimeString($start, $end = null, $limit = null, $filter = true, $suffix = 'ago', $format = 'Y-m-d', $separator = ' ', $minimum = 1)
{
    $dates = (object) array(
        'start' => new DateTime($start ? : 'now'),
        'end' => new DateTime($end ? : 'now'),
        'intervals' => array('y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second'),
        'periods' => array()
    );
    $elapsed = (object) array(
        'interval' => $dates->start->diff($dates->end),
        'unknown' => 'unknown'
    );
    if ($elapsed->interval->invert === 1) {
        return trim('0 seconds ' . $suffix);
    }
    if (false === empty($limit)) {
        $dates->limit = new DateTime($limit);
        if (date_create()->add($elapsed->interval) > $dates->limit) {
            return $dates->start->format($format) ? : $elapsed->unknown;
        }
    }
    if (true === is_array($filter)) {
        $dates->intervals = array_intersect($dates->intervals, $filter);
        $filter = false;
    }
    foreach ($dates->intervals as $period => $name) {
        $value = $elapsed->interval->$period;
        if ($value >= $minimum) {
            $dates->periods[] = vsprintf('%1$s %2$s%3$s', array($value, $name, ($value !== 1 ? 's' : '')));
            if (true === $filter) {
                break;
            }
        }
    }
    if (false === empty($dates->periods)) {
        return trim(vsprintf('%1$s %2$s', array(implode($separator, $dates->periods), $suffix)));
    }

    return $dates->start->format($format) ? : $elapsed->unknown;
}

需要注意的一点 - 所提供过滤器值的检索间隔不会延续到下一个周期。过滤器仅显示提供的周期的结果值,并且不会重新计算周期以仅显示所需的过滤器总数。


用法

由于 OP 需要显示最高时段(截至 2015-02-24)。

echo elapsedTimeString('2010-04-26');
/** 4 years ago */

显示复合期间并提供自定义结束日期(请注意缺少提供的时间和虚构的日期)

echo elapsedTimeString('1920-01-01', '2500-02-24', null, false);
/** 580 years 1 month 23 days ago */

显示过滤周期的结果(数组的顺序无关紧要).

echo elapsedTimeString('2010-05-26', '2012-02-24', null, ['month', 'year']);
/** 1 year 8 months ago */

如果达到限制,则以提供的格式(默认 Y-m-d)显示开始日期。

echo elapsedTimeString('2010-05-26', '2012-02-24', '1 year');
/** 2010-05-26 */

还有很多其他用例。它也可以很容易地适应接受 unix 时间戳和/或 DateInterval 对象作为开始、结束或限制参数。

【讨论】:

    【解决方案3】:

    想要分享 php 函数,该函数会导致语法正确的 Facebook 像人类可读的时间格式。

    例子:

    echo get_time_ago(strtotime('now'));
    

    结果:

    不到 1 分钟前

    function get_time_ago($time_stamp)
    {
        $time_difference = strtotime('now') - $time_stamp;
    
        if ($time_difference >= 60 * 60 * 24 * 365.242199)
        {
            /*
             * 60 seconds/minute * 60 minutes/hour * 24 hours/day * 365.242199 days/year
             * This means that the time difference is 1 year or more
             */
            return get_time_ago_string($time_stamp, 60 * 60 * 24 * 365.242199, 'year');
        }
        elseif ($time_difference >= 60 * 60 * 24 * 30.4368499)
        {
            /*
             * 60 seconds/minute * 60 minutes/hour * 24 hours/day * 30.4368499 days/month
             * This means that the time difference is 1 month or more
             */
            return get_time_ago_string($time_stamp, 60 * 60 * 24 * 30.4368499, 'month');
        }
        elseif ($time_difference >= 60 * 60 * 24 * 7)
        {
            /*
             * 60 seconds/minute * 60 minutes/hour * 24 hours/day * 7 days/week
             * This means that the time difference is 1 week or more
             */
            return get_time_ago_string($time_stamp, 60 * 60 * 24 * 7, 'week');
        }
        elseif ($time_difference >= 60 * 60 * 24)
        {
            /*
             * 60 seconds/minute * 60 minutes/hour * 24 hours/day
             * This means that the time difference is 1 day or more
             */
            return get_time_ago_string($time_stamp, 60 * 60 * 24, 'day');
        }
        elseif ($time_difference >= 60 * 60)
        {
            /*
             * 60 seconds/minute * 60 minutes/hour
             * This means that the time difference is 1 hour or more
             */
            return get_time_ago_string($time_stamp, 60 * 60, 'hour');
        }
        else
        {
            /*
             * 60 seconds/minute
             * This means that the time difference is a matter of minutes
             */
            return get_time_ago_string($time_stamp, 60, 'minute');
        }
    }
    
    function get_time_ago_string($time_stamp, $divisor, $time_unit)
    {
        $time_difference = strtotime("now") - $time_stamp;
        $time_units      = floor($time_difference / $divisor);
    
        settype($time_units, 'string');
    
        if ($time_units === '0')
        {
            return 'less than 1 ' . $time_unit . ' ago';
        }
        elseif ($time_units === '1')
        {
            return '1 ' . $time_unit . ' ago';
        }
        else
        {
            /*
             * More than "1" $time_unit. This is the "plural" message.
             */
            // TODO: This pluralizes the time unit, which is done by adding "s" at the end; this will not work for i18n!
            return $time_units . ' ' . $time_unit . 's ago';
        }
    }
    

    【讨论】:

    • 它给出了这个字符串 -170 minutes ago 为什么减号以及为什么它在 2 小时前没有返回
    • 你写了什么代码?这个例子工作正常echo get_time_ago(strtotime('-2 hours'));
    • 我在 mysql 中有一个 DATETIME 字段,我按原样检索并传递给这个函数..get_time_ago(strtotime(datetime value from db))...你知道 mysql 'Ymd 的日期格式H:i:s' .....我尝试了使用和不使用 strtotime ......但没有奏效......请帮助
    • 现在我将我的日期时间值转换为时间戳并传递给函数,它开始正常工作,我上传了一个新帖子,它应该将日期显示为“不到 1 分钟前”,但它显示“- 210 分钟前'
    • 确保您的 PHP 服务器和数据库都设置了相同的时区。
    【解决方案4】:

    大多数答案似乎都集中在将日期从字符串转换为时间。看来您主要是考虑将日期转换为“5 天前”格式等。对吗?

    这就是我要这样做的方式:

    $time = strtotime('2010-04-28 17:25:43');
    
    echo 'event happened '.humanTiming($time).' ago';
    
    function humanTiming ($time)
    {
    
        $time = time() - $time; // to get the time since that moment
        $time = ($time<1)? 1 : $time;
        $tokens = array (
            31536000 => 'year',
            2592000 => 'month',
            604800 => 'week',
            86400 => 'day',
            3600 => 'hour',
            60 => 'minute',
            1 => 'second'
        );
    
        foreach ($tokens as $unit => $text) {
            if ($time < $unit) continue;
            $numberOfUnits = floor($time / $unit);
            return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
        }
    
    }
    

    我还没有测试过,但它应该可以工作。

    结果会是这样的

    event happened 4 days ago
    

    event happened 1 minute ago
    

    干杯

    【讨论】:

    • 为什么从最小到最大创建数组只调用array_reverse?无论如何,我相信您需要将“preserve_keys”作为第二个参数传递给 array_reverse。
    • 倒车的好处。我没有尝试过代码,所以我猜你对 preserve_keys 是正确的。
    • 这是一个好的开始,但它只是一个除法,而 floor 的意思是“至少发生在 1 天前”等等......你的代码的真正意思是“它发生在 4 天 3 小时前” .
    • 它有点工作,但缺少小时和分钟......
    • @SwatantraK 这不是不可靠的证明,只是不同的方法
    【解决方案5】:

    尝试以下代码库之一:

    https://github.com/salavert/time-ago-in-words

    https://github.com/jimmiw/php-time-ago

    我刚开始使用后者,确实可以,但是当相关日期太远时,没有stackoverflow风格的回退到确切日期,也不支持未来的日期 - 而且API有点时髦,但是至少它看起来完美无瑕并且得到维护......

    【讨论】:

      【解决方案6】:

      最近不得不这样做 - 希望这对某人有所帮助。它不能满足所有可能性,但满足了我对项目的需求。

      https://github.com/duncanheron/twitter_date_format

      https://github.com/duncanheron/twitter_date_format/blob/master/twitter_date_format.php

      【讨论】:

        【解决方案7】:

        arnorhs 对“humanTiming”功能的即兴创作。它将计算时间字符串到人类可读文本版本的“完全拉伸”翻译。比如说“1周2天1小时28分14秒”

        function humantime ($oldtime, $newtime = null, $returnarray = false)    {
            if(!$newtime) $newtime = time();
            $time = $newtime - $oldtime; // to get the time since that moment
            $tokens = array (
                    31536000 => 'year',
                    2592000 => 'month',
                    604800 => 'week',
                    86400 => 'day',
                    3600 => 'hour',
                    60 => 'minute',
                    1 => 'second'
            );
            $htarray = array();
            foreach ($tokens as $unit => $text) {
                    if ($time < $unit) continue;
                    $numberOfUnits = floor($time / $unit);
                    $htarray[$text] = $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
                    $time = $time - ( $unit * $numberOfUnits );
            }
            if($returnarray) return $htarray;
            return implode(' ', $htarray);
        }
        

        【讨论】:

          【解决方案8】:

          使用这个,你可以得到

              $previousDate = '2013-7-26 17:01:10';
              $startdate = new DateTime($previousDate);
              $endDate   = new DateTime('now');
              $interval  = $endDate->diff($startdate);
              echo$interval->format('%y years, %m months, %d days');
          

          参考这个 http://ca2.php.net/manual/en/dateinterval.format.php

          【讨论】:

          • %d 不适用于“几天前”。请改用%R%a
          【解决方案9】:

          我喜欢 Mithun 的代码,但我对其进行了一些调整以使其给出更合理的答案。

          function getTimeSince($eventTime)
          {
              $totaldelay = time() - strtotime($eventTime);
              if($totaldelay <= 0)
              {
                  return '';
              }
              else
              {
                  $first = '';
                  $marker = 0;
                  if($years=floor($totaldelay/31536000))
                  {
                      $totaldelay = $totaldelay % 31536000;
                      $plural = '';
                      if ($years > 1) $plural='s';
                      $interval = $years." year".$plural;
                      $timesince = $timesince.$first.$interval;
                      if ($marker) return $timesince;
                      $marker = 1;
                      $first = ", ";
                  }
                  if($months=floor($totaldelay/2628000))
                  {
                      $totaldelay = $totaldelay % 2628000;
                      $plural = '';
                      if ($months > 1) $plural='s';
                      $interval = $months." month".$plural;
                      $timesince = $timesince.$first.$interval;
                      if ($marker) return $timesince;
                      $marker = 1;
                      $first = ", ";
                  }
                  if($days=floor($totaldelay/86400))
                  {
                      $totaldelay = $totaldelay % 86400;
                      $plural = '';
                      if ($days > 1) $plural='s';
                      $interval = $days." day".$plural;
                      $timesince = $timesince.$first.$interval;
                      if ($marker) return $timesince;
                      $marker = 1;
                      $first = ", ";
                  }
                  if ($marker) return $timesince;
                  if($hours=floor($totaldelay/3600))
                  {
                      $totaldelay = $totaldelay % 3600;
                      $plural = '';
                      if ($hours > 1) $plural='s';
                      $interval = $hours." hour".$plural;
                      $timesince = $timesince.$first.$interval;
                      if ($marker) return $timesince;
                      $marker = 1;
                      $first = ", ";
          
                  }
                  if($minutes=floor($totaldelay/60))
                  {
                      $totaldelay = $totaldelay % 60;
                      $plural = '';
                      if ($minutes > 1) $plural='s';
                      $interval = $minutes." minute".$plural;
                      $timesince = $timesince.$first.$interval;
                      if ($marker) return $timesince;
                      $first = ", ";
                  }
                  if($seconds=floor($totaldelay/1))
                  {
                      $totaldelay = $totaldelay % 1;
                      $plural = '';
                      if ($seconds > 1) $plural='s';
                      $interval = $seconds." second".$plural;
                      $timesince = $timesince.$first.$interval;
                  }        
                  return $timesince;
          
              }
          }
          

          【讨论】:

            【解决方案10】:

            您可以直接从 WordPress 核心文件中获取此功能,看看这里

            http://core.trac.wordpress.org/browser/tags/3.6/wp-includes/formatting.php#L2121

            function human_time_diff( $from, $to = '' ) {
                if ( empty( $to ) )
                    $to = time();
            
                $diff = (int) abs( $to - $from );
            
                if ( $diff < HOUR_IN_SECONDS ) {
                    $mins = round( $diff / MINUTE_IN_SECONDS );
                    if ( $mins <= 1 )
                        $mins = 1;
                    /* translators: min=minute */
                    $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
                } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
                    $hours = round( $diff / HOUR_IN_SECONDS );
                    if ( $hours <= 1 )
                        $hours = 1;
                    $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
                } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
                    $days = round( $diff / DAY_IN_SECONDS );
                    if ( $days <= 1 )
                        $days = 1;
                    $since = sprintf( _n( '%s day', '%s days', $days ), $days );
                } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
                    $weeks = round( $diff / WEEK_IN_SECONDS );
                    if ( $weeks <= 1 )
                        $weeks = 1;
                    $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
                } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
                    $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
                    if ( $months <= 1 )
                        $months = 1;
                    $since = sprintf( _n( '%s month', '%s months', $months ), $months );
                } elseif ( $diff >= YEAR_IN_SECONDS ) {
                    $years = round( $diff / YEAR_IN_SECONDS );
                    if ( $years <= 1 )
                        $years = 1;
                    $since = sprintf( _n( '%s year', '%s years', $years ), $years );
                }
            
                return $since;
            }
            
            【解决方案11】:

            这里我使用自定义函数来查找自日期时间以来经过的时间。

            echo Datetodays('2013-7-26 17:01:10'); 功能日期($d){ $date_start = $d; $date_end = date('Y-m-d H:i:s'); 定义('第二',1); 定义('分钟',秒 * 60); 定义('小时',分钟 * 60); 定义('天',小时* 24); 定义('星期',天 * 7); $t1 = strtotime($date_start); $t2 = strtotime($date_end); 如果($t1 > $t2){ $差异 = $t1 - $t2; } 别的 { $差异 = $t2 - $t1; } //echo "
            ".$date_end." ".$date_start." ".$diffrence; $results['major'] = array(); // 整数表示日期时间关系中的较大数字 $results1 = 数组(); $字符串 = ''; $results['major']['weeks'] = floor($diffrence / WEEK); $results['major']['days'] = floor($diffrence / DAY); $results['major']['hours'] = floor($diffrence / HOUR); $results['major']['minutes'] = floor($diffrence / MINUTE); $results['major']['seconds'] = floor($diffrence / SECOND); //print_r($results); // 逻辑: // 第 1 步:取主要结果并将其转换为原始秒数(将减去差的秒数) // 例如:$result = ($results['major']['weeks']*WEEK) // 第 2 步:从差值(总时间)中减去较小的数字(结果) // 例如:$minor_result = $difference - $result // 第 3 步:以秒为单位获取结果时间并将其转换为次要格式 // 例如:地板($minor_result/DAY) $results1['weeks'] = floor($diffrence / WEEK); $results1['days'] = floor((($diffrence - ($results['major']['weeks'] * WEEK)) / DAY)); $results1['hours'] = floor((($diffrence - ($results['major']['days'] * DAY)) / HOUR)); $results1['minutes'] = floor((($diffrence - ($results['major']['hours'] * HOUR)) / MINUTE)); $results1['seconds'] = floor((($diffrence - ($results['major']['minutes'] * MINUTE)) / SECOND)); //print_r($results1); if ($results1['weeks'] != 0 && $results1['days'] == 0) { if ($results1['weeks'] == 1) { $string = $results1['weeks'] 。 ' 一周前'; } 别的 { if ($results1['weeks'] == 2) { $string = $results1['weeks'] 。 ' 几周前'; } 别的 { $string = '2 周前'; } } } elseif ($results1['weeks'] != 0 && $results1['days'] != 0) { if ($results1['weeks'] == 1) { $string = $results1['weeks'] 。 ' 一周前'; } 别的 { if ($results1['weeks'] == 2) { $string = $results1['weeks'] 。 ' 几周前'; } 别的 { $string = '2 周前'; } } } elseif ($results1['weeks'] == 0 && $results1['days'] != 0) { if ($results1['days'] == 1) { $string = $results1['days'] 。 '一天前'; } 别的 { $string = $results1['days'] 。 ' 几天前'; } } elseif ($results1['days'] != 0 && $results1['hours'] != 0) { $string = $results1['days'] 。 '天和'。 $results1['小时'] 。 '几小时前'; } elseif ($results1['days'] == 0 && $results1['hours'] != 0) { if ($results1['hours'] == 1) { $string = $results1['hours'] 。 ' 一个小时前'; } 别的 { $string = $results1['hours'] 。 '几小时前'; } } elseif ($results1['hours'] != 0 && $results1['minutes'] != 0) { $string = $results1['hours'] 。 '小时和'。 $results1['分钟'] 。 ' 几分钟前'; } elseif ($results1['hours'] == 0 && $results1['minutes'] != 0) { if ($results1['minutes'] == 1) { $string = $results1['分钟'] 。 '分钟前'; } 别的 { $string = $results1['分钟'] 。 ' 几分钟前'; } } elseif ($results1['minutes'] != 0 && $results1['seconds'] != 0) { $string = $results1['分钟'] 。 '分钟和'。 $results1['seconds'] 。 '几秒钟前'; } elseif ($results1['minutes'] == 0 && $results1['seconds'] != 0) { if ($results1['seconds'] == 1) { $string = $results1['seconds'] 。 '第二之前'; } 别的 { $string = $results1['seconds'] 。 '几秒钟前'; } } 返回$字符串; } ?>

            【讨论】:

              【解决方案12】:

              如果你使用 php Datetime 类,你可以使用:

              function time_ago(Datetime $date) {
                $time_ago = '';
              
                $diff = $date->diff(new Datetime('now'));
              
              
                if (($t = $diff->format("%m")) > 0)
                  $time_ago = $t . ' months';
                else if (($t = $diff->format("%d")) > 0)
                  $time_ago = $t . ' days';
                else if (($t = $diff->format("%H")) > 0)
                  $time_ago = $t . ' hours';
                else
                  $time_ago = 'minutes';
              
                return $time_ago . ' ago (' . $date->format('M j, Y') . ')';
              }
              

              【讨论】:

              • 如果您将 else-if 更改为简单的 if 语句,您可能会在数月数天数小时数秒前输出(但我觉得它太混乱了)。
              【解决方案13】:

              自己写的

              function getElapsedTime($eventTime)
              {
                  $totaldelay = time() - strtotime($eventTime);
                  if($totaldelay <= 0)
                  {
                      return '';
                  }
                  else
                  {
                      if($days=floor($totaldelay/86400))
                      {
                          $totaldelay = $totaldelay % 86400;
                          return $days.' days ago.';
                      }
                      if($hours=floor($totaldelay/3600))
                      {
                          $totaldelay = $totaldelay % 3600;
                          return $hours.' hours ago.';
                      }
                      if($minutes=floor($totaldelay/60))
                      {
                          $totaldelay = $totaldelay % 60;
                          return $minutes.' minutes ago.';
                      }
                      if($seconds=floor($totaldelay/1))
                      {
                          $totaldelay = $totaldelay % 1;
                          return $seconds.' seconds ago.';
                      }
                  }
              }
              

              【讨论】:

              • 至少我的代码没有任何 for 循环。并且没有不尊重的行为,因为我遵循了这里回答的人指示的方式。
              【解决方案14】:

              我想我有一个功能可以做你想做的事:

              function time2string($timeline) {
                  $periods = array('day' => 86400, 'hour' => 3600, 'minute' => 60, 'second' => 1);
              
                  foreach($periods AS $name => $seconds){
                      $num = floor($timeline / $seconds);
                      $timeline -= ($num * $seconds);
                      $ret .= $num.' '.$name.(($num > 1) ? 's' : '').' ';
                  }
              
                  return trim($ret);
              }
              

              只需将其应用于time()strtotime('2010-04-28 17:25:43') 之间的差异,如下所示:

              print time2string(time()-strtotime('2010-04-28 17:25:43')).' ago';
              

              【讨论】:

              • 会返回一个类似“3 小时 5 分 6 秒前”的字符串,对吧?
              • 是的,会的。可能有点误读了 OP 的问题,在这种情况下,需要对其使用进行一些调整。
              • 这对我来说非常有效,并且比选择的答案 IMO 好得多。谢谢。 +1
              • @JoeR 非常感谢!此类任务并不经常遇到,但一旦遇到,就很难快速找到解决方案。但是你和我们分享了,谢谢!
              【解决方案15】:

              适用于任何版本的 PHP 的一个选项是执行已经建议的操作,如下所示:

              $eventTime = '2010-04-28 17:25:43';
              $age = time() - strtotime($eventTime);
              

              这将以秒为单位给出您的年龄。从那里,您可以随心所欲地显示它。

              但是,这种方法的一个问题是它不会考虑 DST 导致的时间偏移。如果这不是一个问题,那就去吧。否则,您可能需要使用diff() method in the DateTime class。不幸的是,如果您至少使用 PHP 5.3,这只是一个选项。

              【讨论】:

              【解决方案16】:

              要找出经过的时间,我通常使用time() 而不是date() 和格式化的时间戳。 然后得到后一个值和前一个值之间的差异并相应地格式化。 time() 不是 date() 的替代品,但它在计算经过的时间时完全有帮助。

              示例:

              time() 的值看起来像这样1274467343 每秒钟递增一次。所以你可以让$erlierTime 的值为1274467343$latterTime 的值为1274467500,然后只需执行$latterTime - $erlierTime 即可获得以秒为单位的时间。

              【讨论】:

                【解决方案17】:

                将 [saved_date] 转换为时间戳。获取当前时间戳。

                当前时间戳 - [saved_date] 时间戳。

                然后你可以用 date(); 格式化它

                您通常可以使用 strtotime() 函数将大多数日期格式转换为时间戳。

                【讨论】:

                • 不幸的是 date() 不允许计算两个日期之间的天数/分钟...
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2012-01-03
                • 2014-11-10
                • 1970-01-01
                • 1970-01-01
                • 2023-03-12
                • 1970-01-01
                相关资源
                最近更新 更多