Technology

Implementing Real-time Timestamp Displays in JavaScript

Learn how to implement a JavaScript function for displaying real-time, relative timestamps like 'hours ago', 'minutes ago', and 'seconds ago' easily on your website, inspired by popular social media platforms.

Sangrak

Influenced by the trend on social media platforms, many websites now opt to display the creation time of comments or brief posts in a much more user-friendly manner such as 'X hours ago', 'X minutes ago', and 'X seconds ago'. In a recent CMS project I worked on, I extensively utilized this format for time expression and found the need for an easy method of implementation, leading me to develop a handy function for this purpose about six months ago. At that time, I struggled to find comprehensive guides on such functions through Google searches, and it seems there's still a scarcity of resources on this topic. Thus, I decided on a convenient approach involving the addition of a 'timestamp' attribute to span tags. After several adjustments, I realized the code requires some clean-up, and although it relies on functions from other libraries compromising its performance slightly, I've decided to share the current script in use.

Principle

<span class="_timestamp" timestamp="1312265402">August 2, 2011 15:10:02</span> 

Inputting HTML as shown above automatically transforms it into expressions like 'seconds ago'. This conversion is performed through JavaScript, a method not detectable by search engine bots. Therefore, to ensure search engine crawlers can accurately pick up the date, it's essential to represent it directly within the span tag's innerHTML. The mechanism of updating to phrases like 'seconds ago' involves setting intervals through functions like setInterval, which continuously calculate the time on the webpage. These functions look for 'span._timestamp' elements, check for the 'timestamp' attribute, and compare it to the current time to calculate the difference in seconds or hours, updating the innerHTML of span._timestamp accordingly.

Dependencies

jQuery

Tested with jQuery 1.6, compatibility with other versions not guaranteed but possible with minor adjustments. Visit jQuery.

php.js

A library that implements PHP functions in JavaScript, requiring the date() and strtotime() functions, available at date function and strtotime function.

Adding Method to JavaScript Date Object

Date.prototype.getDOY = function() { 
   var onejan = new Date(this.getFullYear(),0,1); 
   return Math.ceil((this - onejan) / 86400000); 

} 

This function calculates the Day Of Year, a necessary component.

Real-time Timestamp Function

The core JavaScript for calculating time is as follows, with a dependency solely on the date() function.

function dynamicDate(dt, option, nocalcserverdif){ 
   if (typeof timeDif == "undefined") timeDif = 0; 
   
   if (!nocalcserverdif) 
   { 
   	dt += timeDif; 
   } 
   var dif = Math.floor(new Date().getTime() / 1000) - dt; 
   
   switch(option) 
   { 
   	... long function implementation ... 
   } 
} 

Test the function:

alert(dynamicDate(1312265402)); 

A function for live updates:

jQuery(function(){ 
   refreshDate = function(){ 
   	$("span._timestamp").each(function(i,o){ 
   		var oT = $(o); 
   		var timestamp = oT.attr("timestamp"); 
   		var date = oT.attr("date"); 
   		if (date) timestamp = strtotime(date); 
   		timestamp = parseInt(timestamp); 
   		if (isNaN(timestamp)) return true; 
   		if (oT.attr("clientside")) nocalcserverdif = true; 
   		oT.html(dynamicDate(timestamp, oT.attr('option'), nocalcserverdif)); 
   	}); 
   } 
   
   refreshDate(); 
   setInterval(function(){refreshDate()}, 5000); 
}); 

Implement as follows in a jQuery(function(){}) block to ensure functionality post-JQuery and page load. Updates every 5 seconds.

Usage

Implementing the function can be done as easily as inserting the below PHP source code to automatically display the time. The 'option' attribute is optional and can include values like 'half'.

$time = time(); 
echo '<span class="_timestamp" timestamp="'.$time.'" option="half">'.date("Y/m/d H:i:s", $time).'</span> 

Or by using the following expression, requiring the strtotime() function.

<span class="_timestamp" date="August 2, 2011 15:34:02">August 2, 2011 15:34:02</span> 

Example Expression

'August 2, 2011 15:34:02' is presented as August 2, 2011 15:34:02 from now.

Additional Measures

Using span tags might not always reflect the immediate parent element's CSS styles in certain browsers. Additionally, using universal CSS resets can set default text colors and font sizes for all elements. Include the following CSS for more flexible operation:

span._timestamp	{ color: inherit; font-family: inherit; font-size: inherit; } 

Download and Demo

Demo page: See the demo Download: Download the script

More on this topic