phptimestamp

Convert timestamp like Facebook and Twitter


I am fetching time from server like this: 25-07-2015 12:25:28
Now I want to show it like this:
a few second ago
1 minute ago
30 minutes ago
1 Hour ago
12 Hours ago
and after 24 Hours ago
show me the date of that day like :
25 August 2015


Solution

  • the following code works. But no data validation done (eg: old>new)

     <?php
    $olddate = "25-08-2015 15:35:28";       //date as string
    $now = time();                  //pick present time from server     
    $old = strtotime( $olddate);  //create integer value of old time
    $diff =  $now-$old;             //calculate difference
    $old = new DateTime($olddate);
    $old = $old->format('Y M d');       //format date to "2015 Aug 2015" format
    
        if ($diff /60 <1)                       //check the difference and do echo as required
        {
        echo intval($diff%60)."seconds ago";
        }
        else if (intval($diff/60) == 1) 
        {
        echo " 1 minute ago";
        }
        else if ($diff / 60 < 60)
        {
        echo intval($diff/60)."minutes ago";
        }
        else if (intval($diff / 3600) == 1)
        {
        echo "1 hour ago";
        }
        else if ($diff / 3600 <24)
        {
        echo intval($diff/3600) . " hours ago";
        }
        else if ($diff/86400 < 30)
        {
        echo intval($diff/86400) . " days ago";
        }
        else
        {
        echo $old;  ////format date to "2015 Aug 2015" format
        }
    ?>
    

    Change the looping if you can. Logic remains same.