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.
- var listItems;
- var ModifiedDate;
- ExecuteOrDelayUntilScriptLoaded(function () {
- var ctx = SP.ClientContext.get_current();
- var web = ctx.get_web();
- var lists = web.get_lists();
- var list = lists.getByTitle("CustomList");
- ctx.load(list, "LastItemModifiedDate");
-
- var query = new SP.CamlQuery();
-
- query.set_viewXml("");
- listItems = list.getItemById('1');
- ctx.load(listItems);
- ctx.executeQueryAsync(
- function () {
- if(listItems.get_count() > 0)
- {
- ModifiedDate= latestItem.get_item("Modified");
-
- }
- },
- function () {
- }
- );
- }, "sp.js");
- var timesago=getTimesago(ModifiedDate);
Call this re-usable JavaScript Function.
- function getTimesago(date) {
-
- var seconds = Math.floor((new Date() - date) / 1000);
-
- var interval = Math.floor(seconds / 31536000);
-
- if (interval > 1) {
- return interval + " years";
- }
- interval = Math.floor(seconds / 2592000);
- if (interval > 1) {
- return interval + " months";
- }
- interval = Math.floor(seconds / 86400);
- if (interval > 1) {
- return interval + " days";
- }
- interval = Math.floor(seconds / 3600);
- if (interval > 1) {
- return interval + " hours";
- }
- interval = Math.floor(seconds / 60);
- if (interval > 1) {
- return interval + " minutes";
- }
- return Math.floor(seconds) + " seconds";
-
- } 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!!!