How to Convert time...
 

How to Convert timestamp to time ago in PHP ?

2 Posts
1 Users
0 Likes
683 Views
Avatar of admin
(@mjv119gmail-com)
Estimable Member Admin
Joined: 10 years ago
Posts: 79
Topic starter  

How to Convert timestamp to time ago in PHP ?


   
ReplyQuote
Topic Tags
Avatar of admin
(@mjv119gmail-com)
Estimable Member Admin
Joined: 10 years ago
Posts: 79
Topic starter  

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

 


   
ReplyQuote

Leave a reply

Author Name

Author Email

Title *

 
Preview 0 Revisions Saved
Share: