i have a time ago script that changes a unix stamp to a approx time in the form of eg: 1 Min

my script (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
 ?> 

My Question:how do i modify this script to show unix timestamp which results in and approx time older than 2years in to a dd-mm-yyyy format


Explaination for those who didn't understand

a test code/script

 <?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] ;
 ?>

the above code will convert the unix time stamp "946681200" into an approx time ie.14yrs but i want to display all unix time stamps of greater than two years in the DD-MM-YYYY format

有帮助吗?

解决方案

All this code does is create two DateTime objects: one representing two years ago, one representing your initialize time. It then compares them (DateTime objects are comparable). If $initial_date is greater than two years ago it just assigns that date in the format you requested to $time_elapse. Otherwise your code runs as usual.

<?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] ;
  }
 ?>

Demo

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top