Facebook Style time ago function using PHP

Webs Codex
2 min readOct 10, 2023

--

In this tutorial you’ll learn How to get Facebook, Instagram, WhatsApp and so many social media platform style time ago function in PHP. Friends When you use Facebook and update a status on your wall or upload a photo to your Facebook wall, after uploading, the time will be shown as Now or you can also see the time of the previous post, it is the week, month , year or day. In this tutorial we will learn how to save this time using the PHP programming language.

This is a very simple PHP script to get output like Facebook style some time ago. In this function we can calculate the time based on the time zone of a specific country.

If you have a previous date and time, this function will count the time between the current date and time and the previous date using simple PHP logic.

Time Ago Function in PHP

function.php

<?php

date_default_timezone_set("Asia/Calcutta"); //India time (GMT+5:30)

function facebookTimeAgo($timestamp)
{
$time_ago = strtotime($timestamp);
$current_time = time();
$time_difference = $current_time - $time_ago;
$seconds = $time_difference;
$minutes = round($seconds / 60); // value 60 is seconds
$hours = round($seconds / 3600); //value 3600 is 60 minutes * 60 sec
$days = round($seconds / 86400); //86400 = 24 * 60 * 60;
$weeks = round($seconds / 604800); // 7*24*60*60;
$months = round($seconds / 2629440); //((365+365+365+365+366)/5/12)*24*60*60
$years = round($seconds / 31553280); //(365+365+365+365+366)/5 * 24 * 60 * 60

if ($seconds <= 60) {
return "Just Now";
} else if ($minutes <= 60) {

if ($minutes == 1) {
return "one minute ago";
} else {
return "$minutes minutes ago";
}

} else if ($hours <= 24) {
if ($hours == 1) {
return "an hour ago";
} else {
return "$hours hrs ago";
}
} else if ($days <= 7) {
if ($days == 1) {
return "yesterday";
} else {
return "$days days ago";
}
} else if ($weeks <= 4.3) //4.3 == 52/12
{
if ($weeks == 1) {
return "a week ago";
} else {
return "$weeks weeks ago";
}
} else if ($months <= 12) {
if ($months == 1) {
return "a month ago";
} else {
return "$months months ago";
}
} else {
if ($years == 1) {
return "one year ago";
} else {
return "$years years ago";
}
}
}
?>

--

--

Webs Codex
Webs Codex

Written by Webs Codex

Webs Codex is programming and web development blog

No responses yet