Topic starter
01/02/2022 9:49 pm
How to Convert timestamp to time ago in PHP ?
Topic starter
01/02/2022 9:57 pm
Change Asia/kolkata to the timezone of time you are passing as parameter ($time).
<?php
function get_time_ago( $time, $long_time_ago_format = false ) {
// Getting current time
$current_time = new DateTime;
// Set timezone of the time passed as argument
$given_time = new DateTime( $time, new DateTimeZone( "Asia/Kolkata" ) );
$time_diff = $current_time->diff( $given_time );
$time_diff->w = floor( $time_diff->d / 7 );
$time_diff->d -= $time_diff->w * 7;
$time_string_builder = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ( $time_string_builder as $k => &$v ) {
if ( $time_diff->$k ) {
$v = $time_diff->$k . ' ' . $v . ( $time_diff->$k > 1 ? 's' : '' );
} else {
unset( $time_string_builder[ $k ] );
}
}
// Get short form of time ago
if ( ! $long_time_ago_format ) {
$time_string_builder = array_slice( $time_string_builder, 0, 1 );
}
return $time_string_builder ? implode( ', ', $time_string_builder ) . ' ago' : 'just now';
}
// Get short time ago format
get_time_ago(2022-01-02 10:15:00)
// Get long time ago format
get_time_ago(2022-01-02 10:15:00, true)
?>
Â
Output:
2 hours ago
2 hours, 9 minutes, 44 seconds ago
Â
