Query Master Query Master - 2 months ago 8
PHP Question

Calculate hours ago using server time in php without any other date

I need to calculate hours using Server time in php without any other or MySQL dates

Server time Screen shot

server time

and I just confuse myself how to convert server time to this hour

(6 hours ago)


Here is my attempt when I tried myself but I am not sure is this correct way or not.

echo $diff = date("H",abs(strtotime(date("Y-m-d h:i:s a")) - strtotime(date("Y-m-d 0:0:0 a"))));

Answer

Try this code :)

<?php
  function timePassed($str) {
    $sec = time() - strtotime($str);
    if($sec < 60) {
      /* if less than a minute, return seconds */
      return $sec . " seconds ago";
    }
    else if($sec < 60*60) {
      /* if less than an hour, return minutes */
      return intval($sec / 60) . " minutes ago";
    }
    else if($sec < 24*60*60) {
      /* if less than a day, return hours */
      return intval($sec / 60 / 60) . " hours ago";
    }
    else {
      /* else returns days */
      return intval($sec / 60 / 60 / 24) . " days ago";
    }
  }

  /* print: 8 hours ago */
  echo timePassed("2012-03-27 05:36:25 am");
?>