Creating a DateTime Time Ago like Social Networking Sites in PHP Tutorial
Introduction
In this tutorial, I will teach you How to create a Time Ago Feature in PHP for your sites. This feature is like you've seen in some other famous social networking sites such as Facebook. This feature represents how old the post, blog, or article on your site is. The tutorial aims to provide IT/CS students or those who are new to PHP Language a reference or guide for learning some different methods or techniques using the said programming language. Here, snippets and sample source codes are provided for free.
What is a Time Ago Feature?
The Time Ago Feature is commonly or mostly found or used in social networking sites. It represents how old the post users or groups have created the post. It is also for some other dynamic sections of the site such as the comment sections. It is mainly added to the site feature for informing the readers of how old the post or content is.
How to create a Time Ago Feature in PHP?
To create a Time Ago Feature on your site, you must make sure that the timestamp or the date and time of creation or insertion of the data is available. Then, you will have to calculate the difference between the created timestamp and the current timestamp which can be achieved in PHP like the following snippet.
- <?php
- // Data Created Timestamp
- // Current Timestamp
- //Calculating the difference between the 2 Timestamps
- $difference = $current_timestamp - $timestamp;
- // The difference of the 2 timestamp will result the time difference in seconds
- // i.e $difference = 62314;
- ?>
On the above PHP script, $differece computes the difference of the timestamp in seconds which means it still needs to convert to minutes, hours, days, weeks, months, and years. These conversions can be achieved using the following formula.
- <?php
- /**Getting the difference by minute(s)
- * timestamp difference / 60
- */
- /**Getting the difference by hour(s)
- * timestamp difference / ( 60 * 60)
- */
- /**Getting the difference by day(s)
- * timestamp difference / ( 24 * 60 * 60)
- */
- /**Getting the difference by week(s)
- * timestamp difference / ( 7 * 24 * 60 * 60)
- */
- /**Getting the difference by month(s)
- * timestamp difference / ( ( ( 365 + 365 + 365 + 365 + 366 ) / 5 / 12 ) * 24 * 60 *60 )
- */
- /**Getting the difference by year(s)
- * timestamp difference / ( ( ( 365 + 365 + 365 + 365 + 366 ) / 5 ) * 24 * 60 *60 )
- */
- ?>
And using the above snippet, you can now create logic for returning the age of the data or article of your site. Your logic can be something like the following snippet.
- <?php
- if( $differece < 60 ){
- if( $differece == 1)
- return "Just Now";
- else
- return "{$differece} seconds ago";
- }elseif($minutes < 60){
- if( $minutes == 1 )
- return "A minute ago";
- else
- return "{$minutes} min. ago";
- }
- ?>
You can create your own PHP function or class object so you can simply call it multiple times without repeating or rewriting the codes. Here's an example reusable function.
- <?php
- function get_timeago($timestamp=""){
- // Check if time stamp is valid
- return "Invalid Date and Time Value";
- // Current Timestamp
- // Getting the difference beteween Current timestamp and given timestamp
- $diff = $current_time - $timestamp;
- // Timeago or timestamp difference in seconds
- $ta_seconds = $diff;
- /**
- * Timestamp Difference (s) Convertions
- */
- /**Getting the difference by minute(s)
- * timestamp difference / 60
- */
- /**Getting the difference by hour(s)
- * timestamp difference / ( 60 * 60)
- */
- /**Getting the difference by day(s)
- * timestamp difference / ( 24 * 60 * 60)
- */
- /**Getting the difference by week(s)
- * timestamp difference / ( 7 * 24 * 60 * 60)
- */
- /**Getting the difference by month(s)
- * timestamp difference / ( ( ( 365 + 365 + 365 + 365 + 366 ) / 5 / 12 ) * 24 * 60 *60 )
- */
- /**Getting the difference by year(s)
- * timestamp difference / ( ( ( 365 + 365 + 365 + 365 + 366 ) / 5 ) * 24 * 60 *60 )
- */
- /**
- * Return Timeago
- */
- if( $ta_seconds < 60 ){
- if( $ta_seconds == 1)
- return "Just Now";
- else
- return "{$ta_seconds} sec. ago";
- }elseif($minutes < 60){
- if( $minutes == 1 )
- return "A minute ago";
- else
- return "{$minutes} min. ago";
- }elseif( $hours < 24 ){
- if( $hours == 1 )
- return "An Hour ago";
- else
- return "{$hours} hr. ago";
- }elseif( $days < 7 ){
- if( $days == 1 )
- return "A day ago";
- else
- return "{$days} days ago";
- }elseif( $weeks < 4 ){
- if( $weeks == 1 )
- return "A week ago";
- else
- return "{$weeks} weeks ago";
- }elseif( $months < 12 ){
- if( $months == 1 )
- return "A month ago";
- else
- return "{$months} months ago";
- }elseif( $years > 0 ){
- if( $years == 1 )
- return "A year ago";
- else
- return "{$years} years ago";
- }elseif($ta_seconds <= -1){
- return "Future/Scheduled";
- }else{
- return "{$weeks} weeks ago";
- }
- }
- ?>
Example
Here is an example program or application that demonstrates how to create a Time Ago Feature in PHP. The script below was only built for educational purposes only.
Interface
index.php
- <?php
- require_once("time_ago_func.php");
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-IDwe1+LCz02ROU9k972gdyvl+AESN10+x7tBKgc9I5HFtuNz0wWnPclzo6p9vxnk" crossorigin="anonymous"></script>
- <style>
- html, body{
- min-height:calc(100%);
- width: calc(100%);
- }
- body{
- min-height: 100vh;
- width: 100vw;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- }
- </style>
- </head>
- <body class="bg-light bg-gradient">
- <div class="container-fluid w-100">
- <div class="col-lg-7 col-md-9 col-sm-12 mx-auto">
- <div class="d-flex justify-content-center">
- <hr class="col-4">
- </div>
- </div>
- <div class="card rounded-0 shadow col-lg-5 col-md-7 col-sm-12 mx-auto">
- <div class="card-body">
- <div class="container-fluid">
- <form action="" id="sample-form" method = "POST">
- <div class="mb-3" id="progress-holder">
- <div id="CurrentTime" class="h2 fw-bold text-center">
- --:--:-- --
- </div>
- </div>
- <div class="mb-3">
- <input class="form-control" type="datetime-local" name="datetime" id="datetime" value="<?= isset($_POST['datetime']) ? $_POST['datetime'] : '' ?>" required>
- </div>
- <div class="mb-3 d-grid">
- </div>
- </form>
- <div class="text-bg-dark px-2 py-3">
- <?php if($_SERVER['REQUEST_METHOD'] == "POST"): ?>
- <dl class="row">
- </dl>
- <dl class="row">
- </dl>
- <?php else: ?>
- <?php endif; ?>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
JS Script
app.js
- var liveClockInvetrval;
- $(document).ready(function(){
- // Live Clock
- liveClockInvetrval = setInterval(function(){
- var current_date = new Date().toLocaleString('en-US', { timeZone: 'Asia/Manila'});
- var new_date = new Date(current_date)
- var h = new_date.getHours();
- var m = new_date.getMinutes();
- var s = new_date.getSeconds();
- var am_pm = h > 12 ? "AM" : "PM";
- h = h > 12 ? h - 12 : (h == 0? 12: h);
- $('#CurrentTime').text(`${h.toString().padStart(2, 0)}:${m.toString().padStart(2, 0)}:${s.toString().padStart(2, 0)} ${am_pm}`)
- },500)
- })
PHP Script
time_ago_func.php
- <?php
- function get_timeago($timestamp=""){
- // Check if time stamp is valid
- return "Invalid Date and Time Value";
- // Current Timestamp
- // Getting the difference beteween Current timestamp and given timestamp
- $diff = $current_time - $timestamp;
- // Timeago or timestamp difference in seconds
- $ta_seconds = $diff;
- /**
- * Timestamp Difference (s) Convertions
- */
- /**Getting the difference by minute(s)
- * timestamp difference / 60
- */
- /**Getting the difference by hour(s)
- * timestamp difference / ( 60 * 60)
- */
- /**Getting the difference by day(s)
- * timestamp difference / ( 24 * 60 * 60)
- */
- /**Getting the difference by week(s)
- * timestamp difference / ( 7 * 24 * 60 * 60)
- */
- /**Getting the difference by month(s)
- * timestamp difference / ( ( ( 365 + 365 + 365 + 365 + 366 ) / 5 / 12 ) * 24 * 60 *60 )
- */
- /**Getting the difference by year(s)
- * timestamp difference / ( ( ( 365 + 365 + 365 + 365 + 366 ) / 5 ) * 24 * 60 *60 )
- */
- /**
- * Return Timeago
- */
- if( $ta_seconds < 60 ){
- if( $ta_seconds == 1)
- return "Just Now";
- else
- return "{$ta_seconds} sec. ago";
- }elseif($minutes < 60){
- if( $minutes == 1 )
- return "A minute ago";
- else
- return "{$minutes} min. ago";
- }elseif( $hours < 24 ){
- if( $hours == 1 )
- return "An Hour ago";
- else
- return "{$hours} hr. ago";
- }elseif( $days < 7 ){
- if( $days == 1 )
- return "A day ago";
- else
- return "{$days} days ago";
- }elseif( $weeks < 4 ){
- if( $weeks == 1 )
- return "A week ago";
- else
- return "{$weeks} weeks ago";
- }elseif( $months < 12 ){
- if( $months == 1 )
- return "A month ago";
- else
- return "{$months} months ago";
- }elseif( $years > 0 ){
- if( $years == 1 )
- return "A year ago";
- else
- return "{$years} years ago";
- }elseif($ta_seconds <= -1){
- return "Future/Scheduled";
- }else{
- return "{$weeks} weeks ago";
- }
- }
- ?>
Snapshot
Here's the snapshot of the page of the sample application using the above scripts.
DEMO VIDEO
That's it! I have also provided a zip file of the complete source code of the above sample application. You can download it by clicking the Download Button below this article.
That's the end of this tutorial. I hope this PHP Tutorial will help you with what you are looking for and that you'll find this useful for your current and future PHP Projects. Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding :)
Add new comment
- 747 views