如何修改time-ago脚本以DD-MM-YYYY的形式显示时间


how to modify time ago script to show time in form of DD-MM-YYYY

我有一个很久以前的脚本,它以eg: 1 Min 的形式将unix戳更改为大约时间

我的脚本(PHP):

<?php
  $periods = array("sec", "min", "hr", "day", "week", "month", "yr");
  $lengths = array("60","60","24","7","4.35","12","10");
  $span     = time() - $row['post_time'];
  $tense    = "ago";
  for($j = 0; $span >= $lengths[$j] && $j < count($lengths)-1; $j++) 
  {
  $span /= $lengths[$j];
  }
  $span = round($span);
  if($span != 1) {
  $periods[$j].= "s";
  }
  $time_elapse = $span.' '.$periods[$j] ; //will output in the form of 1min or 1hr
 ?> 

我的问题:我如何修改此脚本以显示unix时间戳,该时间戳将导致和大约超过2年的时间转换为dd-mm-yyyy格式的


为那些不了解的人解释

测试代码/脚本

 <?php
      $initial_time="946681200";//the unix timestamp is for Jan 1 2001
  $periods = array("sec", "min", "hr", "day", "week", "month", "yr");
  $lengths = array("60","60","24","7","4.35","12","10");
  $span     = time() - $initial_time;
  $tense    = "ago";
  for($j = 0; $span >= $lengths[$j] && $j < count($lengths)-1; $j++) 
  {
  $span /= $lengths[$j];
  }
  $span = round($span);
  if($span != 1) {
  $periods[$j].= "s";
  }
  $time_elapse = $span.' '.$periods[$j] ;
 ?>

上面的代码将unix时间戳"946681200"转换为近似时间,即14yrs,但我希望以DD-MM-YYYY格式

显示所有超过两年的unix时间戳

这些代码所做的就是创建两个DateTime对象:一个表示两年前,一个表示初始化时间。然后对它们进行比较(DateTime对象是可比较的)。如果$initial_date大于两年前,它只会按照您要求的格式将该日期分配给$time_elapse。否则,您的代码将照常运行。

<?php
  $initial_time="946681200";//the unix timestamp is for Dec 31, 1999
  $two_years_ago = new DateTime('-2 years');
  $initial_date  = new DateTime('@' . $initial_time);
  if ($initial_date < $two_years_ago) {
    $time_elapse = $initial_date->format('d-m-Y');
  }
  else {
    $periods = array("sec", "min", "hr", "day", "week", "month", "yr");
      $lengths = array("60","60","24","7","4.35","12","10");
      $span     = time() - $initial_time;
      $tense    = "ago";
      for($j = 0; $span >= $lengths[$j] && $j < count($lengths)-1; $j++) 
      {
      $span /= $lengths[$j];
      }
      $span = round($span);
      if($span != 1) {
      $periods[$j].= "s";
      }
      $time_elapse = $span.' '.$periods[$j] ;
  }
 ?>

演示