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.

  1. <?php
  2. // Data Created Timestamp
  3. $timestamp = strtotime($created_at);
  4.  
  5. // Current Timestamp
  6. $current_timestamp = strtotime('now');
  7.  
  8. //Calculating the difference between the 2 Timestamps
  9. $difference = $current_timestamp - $timestamp;
  10.  
  11. // The difference of the 2 timestamp will result the time difference in seconds
  12. // i.e $difference = 62314;
  13.  
  14. ?>

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.

  1. <?php
  2. /**Getting the difference by minute(s)
  3. * timestamp difference / 60
  4. */
  5. $minutes = round($difference / 60);
  6. /**Getting the difference by hour(s)
  7.   * timestamp difference / ( 60 * 60)
  8.   */
  9. $hours = round($difference / 3600);
  10. /**Getting the difference by day(s)
  11.   * timestamp difference / ( 24 * 60 * 60)
  12.   */
  13. $days = round($difference / 86400);
  14. /**Getting the difference by week(s)
  15. * timestamp difference / ( 7 * 24 * 60 * 60)
  16. */
  17. $weeks = round($difference / 604800);
  18. /**Getting the difference by month(s)
  19. * timestamp difference / ( ( ( 365 + 365 + 365 + 365 + 366 ) / 5 / 12 ) * 24 * 60 *60 )
  20. */
  21. $months = round($difference / 2629440);
  22. /**Getting the difference by year(s)
  23. * timestamp difference / ( ( ( 365 + 365 + 365 + 365 + 366 ) / 5 ) * 24 * 60 *60 )
  24. */
  25. $years = round($difference / 31553280);
  26. ?>

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.

  1. <?php
  2. if( $differece < 60 ){
  3. if( $differece == 1)
  4. return "Just Now";
  5. else
  6. return "{$differece} seconds ago";
  7. }elseif($minutes < 60){
  8. if( $minutes == 1 )
  9. return "A minute ago";
  10. else
  11. return "{$minutes} min. ago";
  12. }
  13. ?>

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.

  1. <?php
  2. function get_timeago($timestamp=""){
  3. // Check if time stamp is valid
  4. if(empty($timestamp) && is_numeric($timestamp) && $timestamp > 0)
  5. return "Invalid Date and Time Value";
  6.  
  7. // Current Timestamp
  8. $current_time = strtotime('now');
  9. // Getting the difference beteween Current timestamp and given timestamp
  10. $diff = $current_time - $timestamp;
  11. // Timeago or timestamp difference in seconds
  12. $ta_seconds = $diff;
  13.  
  14.  
  15. /**
  16.   * Timestamp Difference (s) Convertions
  17.   */
  18.  
  19. /**Getting the difference by minute(s)
  20.   * timestamp difference / 60
  21.   */
  22. $minutes = round($ta_seconds / 60);
  23. /**Getting the difference by hour(s)
  24.   * timestamp difference / ( 60 * 60)
  25.   */
  26. $hours = round($ta_seconds / 3600);
  27. /**Getting the difference by day(s)
  28.   * timestamp difference / ( 24 * 60 * 60)
  29.   */
  30. $days = round($ta_seconds / 86400);
  31. /**Getting the difference by week(s)
  32.   * timestamp difference / ( 7 * 24 * 60 * 60)
  33.   */
  34. $weeks = round($ta_seconds / 604800);
  35. /**Getting the difference by month(s)
  36.   * timestamp difference / ( ( ( 365 + 365 + 365 + 365 + 366 ) / 5 / 12 ) * 24 * 60 *60 )
  37.   */
  38. $months = round($ta_seconds / 2629440);
  39. /**Getting the difference by year(s)
  40.   * timestamp difference / ( ( ( 365 + 365 + 365 + 365 + 366 ) / 5 ) * 24 * 60 *60 )
  41.   */
  42. $years = round($ta_seconds / 31553280);
  43.  
  44.  
  45. /**
  46.   * Return Timeago
  47.   */
  48. if( $ta_seconds < 60 ){
  49. if( $ta_seconds == 1)
  50. return "Just Now";
  51. else
  52. return "{$ta_seconds} sec. ago";
  53. }elseif($minutes < 60){
  54. if( $minutes == 1 )
  55. return "A minute ago";
  56. else
  57. return "{$minutes} min. ago";
  58. }elseif( $hours < 24 ){
  59. if( $hours == 1 )
  60. return "An Hour ago";
  61. else
  62. return "{$hours} hr. ago";
  63. }elseif( $days < 7 ){
  64. if( $days == 1 )
  65. return "A day ago";
  66. else
  67. return "{$days} days ago";
  68. }elseif( $weeks < 4 ){
  69. if( $weeks == 1 )
  70. return "A week ago";
  71. else
  72. return "{$weeks} weeks ago";
  73. }elseif( $months < 12 ){
  74. if( $months == 1 )
  75. return "A month ago";
  76. else
  77. return "{$months} months ago";
  78. }elseif( $years > 0 ){
  79. if( $years == 1 )
  80. return "A year ago";
  81. else
  82. return "{$years} years ago";
  83. }elseif($ta_seconds <= -1){
  84. return "Future/Scheduled";
  85. }else{
  86. return "{$weeks} weeks ago";
  87. }
  88. }
  89. ?>

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

  1. <?php
  2. require_once("time_ago_func.php");
  3. ?>
  4. <!DOCTYPE html>
  5. <html lang="en">
  6. <meta charset="UTF-8">
  7. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  8. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  9. <title>PHP Time Ago Function</title>
  10. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  11. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  12. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-IDwe1+LCz02ROU9k972gdyvl+AESN10+x7tBKgc9I5HFtuNz0wWnPclzo6p9vxnk" crossorigin="anonymous"></script>
  13. html, body{
  14. min-height:calc(100%);
  15. width: calc(100%);
  16. }
  17. body{
  18. min-height: 100vh;
  19. width: 100vw;
  20. display: flex;
  21. flex-direction: column;
  22. align-items: center;
  23. justify-content: center;
  24. }
  25. </style>
  26. </head>
  27. <body class="bg-light bg-gradient">
  28. <div class="container-fluid w-100">
  29. <div class="col-lg-7 col-md-9 col-sm-12 mx-auto">
  30. <h1 class="text-center fw-bolder my-4">Creating a Time Ago Function in PHP like some famous Social Networking Sites</h1>
  31. <div class="d-flex justify-content-center">
  32. <hr class="col-4">
  33. </div>
  34. </div>
  35. <div class="card rounded-0 shadow col-lg-5 col-md-7 col-sm-12 mx-auto">
  36. <div class="card-body">
  37. <div class="container-fluid">
  38. <form action="" id="sample-form" method = "POST">
  39. <div class="mb-3" id="progress-holder">
  40. <div id="CurrentTime" class="h2 fw-bold text-center">
  41. --:--:-- --
  42. </div>
  43. <div class="text-center h4 text-muted">Philippine Standard Time</div>
  44. </div>
  45. <div class="mb-3">
  46. <label for="datetime" class="form-label">Select DateTime</label>
  47. <input class="form-control" type="datetime-local" name="datetime" id="datetime" value="<?= isset($_POST['datetime']) ? $_POST['datetime'] : '' ?>" required>
  48. </div>
  49. <div class="mb-3 d-grid">
  50. <button class="btn btn-sm rounded-pill btn-primary btn-block" type="submit">Submit</button>
  51. </div>
  52. </form>
  53. <div class="text-bg-dark px-2 py-3">
  54. <?php if($_SERVER['REQUEST_METHOD'] == "POST"): ?>
  55. <dl class="row">
  56. <dt class="col-auto pe-2">Date and Time:</dt>
  57. <dd class="col-auto flex-shrink-1 flex-grow-1"><?= date("F d, Y g:i:s A", strtotime($_POST['datetime'])) ?></dd>
  58. </dl>
  59. <dl class="row">
  60. <dt class="col-auto pe-2">Conversion:</dt>
  61. <dd class="col-auto flex-shrink-1 flex-grow-1"><?= get_timeago(strtotime($_POST['datetime'])) ?></dd>
  62. </dl>
  63. <?php else: ?>
  64. <div class="text-center">Select Date and Time First.</div>
  65. <?php endif; ?>
  66. </div>
  67. </div>
  68. </div>
  69. </div>
  70. </div>
  71. </body>
  72.  
  73. <script src="./app.js"></script>
  74. </html>

JS Script

app.js

  1. var liveClockInvetrval;
  2. $(document).ready(function(){
  3. // Live Clock
  4. liveClockInvetrval = setInterval(function(){
  5. var current_date = new Date().toLocaleString('en-US', { timeZone: 'Asia/Manila'});
  6. var new_date = new Date(current_date)
  7.  
  8. var h = new_date.getHours();
  9. var m = new_date.getMinutes();
  10. var s = new_date.getSeconds();
  11. var am_pm = h > 12 ? "AM" : "PM";
  12.  
  13. h = h > 12 ? h - 12 : (h == 0? 12: h);
  14. $('#CurrentTime').text(`${h.toString().padStart(2, 0)}:${m.toString().padStart(2, 0)}:${s.toString().padStart(2, 0)} ${am_pm}`)
  15. },500)
  16.  
  17. })

PHP Script

time_ago_func.php

  1. <?php
  2.  
  3. function get_timeago($timestamp=""){
  4. // Check if time stamp is valid
  5. if(empty($timestamp) && is_numeric($timestamp) && $timestamp > 0)
  6. return "Invalid Date and Time Value";
  7.  
  8. // Current Timestamp
  9. $current_time = strtotime('now');
  10. // Getting the difference beteween Current timestamp and given timestamp
  11. $diff = $current_time - $timestamp;
  12. // Timeago or timestamp difference in seconds
  13. $ta_seconds = $diff;
  14.  
  15.  
  16. /**
  17.   * Timestamp Difference (s) Convertions
  18.   */
  19.  
  20. /**Getting the difference by minute(s)
  21.   * timestamp difference / 60
  22.   */
  23. $minutes = round($ta_seconds / 60);
  24. /**Getting the difference by hour(s)
  25.   * timestamp difference / ( 60 * 60)
  26.   */
  27. $hours = round($ta_seconds / 3600);
  28. /**Getting the difference by day(s)
  29.   * timestamp difference / ( 24 * 60 * 60)
  30.   */
  31. $days = round($ta_seconds / 86400);
  32. /**Getting the difference by week(s)
  33.   * timestamp difference / ( 7 * 24 * 60 * 60)
  34.   */
  35. $weeks = round($ta_seconds / 604800);
  36. /**Getting the difference by month(s)
  37.   * timestamp difference / ( ( ( 365 + 365 + 365 + 365 + 366 ) / 5 / 12 ) * 24 * 60 *60 )
  38.   */
  39. $months = round($ta_seconds / 2629440);
  40. /**Getting the difference by year(s)
  41.   * timestamp difference / ( ( ( 365 + 365 + 365 + 365 + 366 ) / 5 ) * 24 * 60 *60 )
  42.   */
  43. $years = round($ta_seconds / 31553280);
  44.  
  45.  
  46. /**
  47.   * Return Timeago
  48.   */
  49. if( $ta_seconds < 60 ){
  50. if( $ta_seconds == 1)
  51. return "Just Now";
  52. else
  53. return "{$ta_seconds} sec. ago";
  54. }elseif($minutes < 60){
  55. if( $minutes == 1 )
  56. return "A minute ago";
  57. else
  58. return "{$minutes} min. ago";
  59. }elseif( $hours < 24 ){
  60. if( $hours == 1 )
  61. return "An Hour ago";
  62. else
  63. return "{$hours} hr. ago";
  64. }elseif( $days < 7 ){
  65. if( $days == 1 )
  66. return "A day ago";
  67. else
  68. return "{$days} days ago";
  69. }elseif( $weeks < 4 ){
  70. if( $weeks == 1 )
  71. return "A week ago";
  72. else
  73. return "{$weeks} weeks ago";
  74. }elseif( $months < 12 ){
  75. if( $months == 1 )
  76. return "A month ago";
  77. else
  78. return "{$months} months ago";
  79. }elseif( $years > 0 ){
  80. if( $years == 1 )
  81. return "A year ago";
  82. else
  83. return "{$years} years ago";
  84. }elseif($ta_seconds <= -1){
  85. return "Future/Scheduled";
  86. }else{
  87. return "{$weeks} weeks ago";
  88. }
  89. }
  90.  
  91. ?>

Snapshot

Here's the snapshot of the page of the sample application using the above scripts.

PHP Time Ago Feature

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