Hamza Ikine

How To Display Publish Dates Of Articles As Time Since Posted Using HTML and JavaScript

2023-05-05T02:30:00-04:00
image

Problem to Solve:

In this tutorial I will show you how to display the date of a published article as time since it was posted. Instead of showing a date, we will show the reader how much time passed since you posted your article.

The Logic Will Be as Follow:

  • If only 1 minute has passed since the article was posted we will show "Published Just now".
  • If the article was posted less than 60 minutes we will show "Published X minutes ago".
  • If it was posted less than 24 hours we will show "Published X hours ago".
  • If it was posted less than 48 hours we will show "Published Yesterday".
  • And finally if it was published more than 48 hours we will show the actual published date.

Let's Show Our Readers Better Dates:

  1. In your HTML, add a date class to each element that displays the published date. For example:
    				     		  
    <h2>Article Title</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <span class="date">2023-05-05T02:30:00-04:00</span>
    
    
    
    <h2>Another Article Title</h2>
    <p>Nulla facilisi. Curabitur tristique turpis in diam molestie dignissim.</p>
    <span class="date">2023-05-02T02:30:00-04:00</span>
    
    
    				     	   
    				        
  2. We create a function that takes in the published date as a parameter and returns a string with the appropriate units following our logic:
    
    
    function timeSincePost(postDate) {
      const currentDate = new Date();
      const timeDiff = Math.floor((currentDate - postDate) / 60000);
    
      if (timeDiff < 1) {
        return "Published Just now";
      } else if (timeDiff < 60) {
        return `Published ${timeDiff} minutes ago`;
      } else if (timeDiff < 1440) {
        const hoursAgo = Math.floor(timeDiff / 60);
        return `Publlished ${hoursAgo} ${hoursAgo === 1 ? "hour" : "hours"} ago`;
      } else if (timeDiff < 2880) {
        return "Published Yesterday";
      } else {
        // Show the actual published date
        const options = { year: 'numeric', month: 'long', day: 'numeric' };
        return `Published on ${postDate.toLocaleDateString(undefined, options)}`;
      }
    }
    
    				     	
  3. We use the querySelectorAll method to select all articles with the date class:
    
    const dateElements = document.querySelectorAll('.date');
    				     		
  4. Then, we loop through each article to calculate the time elapsed and update the text content:
    
     dateElements.forEach(dateElement => {
             const postDate = new Date(dateElement.textContent);
             const timeAgo = timeSincePost(postDate);
             dateElement.textContent = timeAgo;
      
           });
    				     		

Putting It All Together Your HTML and JavaScript Code Should Look Like This:


<article>
   <h2>Article Title</h2>
   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
   <span class="date">2023-05-05T02:30:00-04:00</span>
</article>

<article>
   <h2>Another Article Title</h2>
   <p>Nulla facilisi. Curabitur tristique turpis in diam molestie dignissim.</p>
   <span class="date">2023-05-02T02:30:00-04:00</span>
</article>		

<!-- more articles with a similar structure -->

<script>
function timeSincePost(postDate) {
  const currentDate = new Date();
  const timeDiff = Math.floor((currentDate - postDate) / 60000);

  if (timeDiff < 1) {
    return "Published Just now";
  } else if (timeDiff < 60) {
    return `Published ${timeDiff} minutes ago`;
  } else if (timeDiff < 1440) {
    const hoursAgo = Math.floor(timeDiff / 60);
    return `Publlished ${hoursAgo} ${hoursAgo === 1 ? "hour" : "hours"} ago`;
  } else if (timeDiff < 2880) {
    return "Published Yesterday";
  } else {
    // Show the actual published date
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    return `Published on ${postDate.toLocaleDateString(undefined, options)}`;
  }
}



      const dateElements = document.querySelectorAll('.date');
       dateElements.forEach(dateElement => {
         const postDate = new Date(dateElement.textContent);
         const timeAgo = timeSincePost(postDate);
         dateElement.textContent = timeAgo;
  
       });
</script>