How to convert timestamp to time ago in PHP ?
Last Updated :
10 Jan, 2019
Given a time and the task is to convert timestamp to time ago. The time ago format removes the problem of different time zones conversions. Given below is a function to do the time conversions. In this function, taking the timestamp as an input and then subtract it from the current timestamp to convert it into the time ago format. To make this function, need to define some rules which determine the year, month, date, minutes etc from the remaining date after subtraction.
Example 1:
<?php
function time_Ago( $time ) {
$diff = time() - $time ;
$sec = $diff ;
$min = round ( $diff / 60 );
$hrs = round ( $diff / 3600);
$days = round ( $diff / 86400 );
$weeks = round ( $diff / 604800);
$mnths = round ( $diff / 2600640 );
$yrs = round ( $diff / 31207680 );
if ( $sec <= 60) {
echo "$sec seconds ago" ;
}
else if ( $min <= 60) {
if ( $min ==1) {
echo "one minute ago" ;
}
else {
echo "$min minutes ago" ;
}
}
else if ( $hrs <= 24) {
if ( $hrs == 1) {
echo "an hour ago" ;
}
else {
echo "$hrs hours ago" ;
}
}
else if ( $days <= 7) {
if ( $days == 1) {
echo "Yesterday" ;
}
else {
echo "$days days ago" ;
}
}
else if ( $weeks <= 4.3) {
if ( $weeks == 1) {
echo "a week ago" ;
}
else {
echo "$weeks weeks ago" ;
}
}
else if ( $mnths <= 12) {
if ( $mnths == 1) {
echo "a month ago" ;
}
else {
echo "$mnths months ago" ;
}
}
else {
if ( $yrs == 1) {
echo "one year ago" ;
}
else {
echo "$yrs years ago" ;
}
}
}
$curr_time = "2013-07-10 09:09:09" ;
$time_ago = strtotime ( $curr_time );
echo time_Ago( $time_ago ) . "\n" ;
$curr_time = "2019-01-05 09:09:09" ;
$time_ago = strtotime ( $curr_time );
echo time_Ago( $time_ago );
?>
|
Output:
6 years ago
5 days ago
Example 2:
<?php
function to_time_ago( $time ) {
$diff = time() - $time ;
if ( $diff < 1 ) {
return 'less than 1 second ago' ;
}
$time_rules = array (
12 * 30 * 24 * 60 * 60 => 'year' ,
30 * 24 * 60 * 60 => 'month' ,
24 * 60 * 60 => 'day' ,
60 * 60 => 'hour' ,
60 => 'minute' ,
1 => 'second'
);
foreach ( $time_rules as $secs => $str ) {
$div = $diff / $secs ;
if ( $div >= 1 ) {
$t = round ( $div );
return $t . ' ' . $str .
( $t > 1 ? 's' : '' ) . ' ago' ;
}
}
}
echo to_time_ago( time() - 5);
?>
|
Share your thoughts in the comments
Please Login to comment...