Sharepoint Datetime Timesago Format Using JavaScript

In this blog, I will explain how to change the SharePoint date format into TimesAgo.

Example
  • 1 minute ago
  • 1 hour ago
  • 1 day ago
  • 1 month ago
  • 1 year ago
First, read the last modified date value from SharePointList.
  1. var listItems;  
  2. var ModifiedDate;  
  1. ExecuteOrDelayUntilScriptLoaded(function () {  
  2.     var ctx = SP.ClientContext.get_current();  
  3.     var web = ctx.get_web();  
  4.     var lists = web.get_lists();  
  5.     var list = lists.getByTitle("CustomList");  
  6.     ctx.load(list, "LastItemModifiedDate");  
  7.   
  8. var query = new SP.CamlQuery();  
  9.    
  10.    query.set_viewXml("");  
  11.         listItems = list.getItemById('1');  
  12.         ctx.load(listItems);  
  13.   ctx.executeQueryAsync(  
  14.         function () {  
  15.        if(listItems.get_count() > 0)  
  16.        {  
  17.            ModifiedDate= latestItem.get_item("Modified");  
  18.              
  19.         }  
  20.         },  
  21.         function () {  
  22.         }  
  23.     );  
  24. }, "sp.js");  
  1. var timesago=getTimesago(ModifiedDate);  
Call this re-usable JavaScript Function.
  1. function getTimesago(date) {  
  2.   
  3.     var seconds = Math.floor((new Date() - date) / 1000);  
  4.   
  5.     var interval = Math.floor(seconds / 31536000);  
  6.   
  7.     if (interval > 1) {  
  8.         return interval + " years";  
  9.     }  
  10.     interval = Math.floor(seconds / 2592000);  
  11.     if (interval > 1) {  
  12.         return interval + " months";  
  13.     }  
  14.     interval = Math.floor(seconds / 86400);  
  15.     if (interval > 1) {  
  16.         return interval + " days";  
  17.     }  
  18.     interval = Math.floor(seconds / 3600);  
  19.     if (interval > 1) {  
  20.         return interval + " hours";  
  21.     }  
  22.     interval = Math.floor(seconds / 60);  
  23.     if (interval > 1) {  
  24.         return interval + " minutes";  
  25.     }  
  26.     return Math.floor(seconds) + " seconds";  
  27.      
  28. alert(timesago)
You will get the output in expected format.

Reference

http://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site
 
Thanks for reading!!!
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now