Wednesday, October 12, 2011

How to show days count after created date of Item in SharePoint list View

There are many posts showing date difference from today's date, but not a exactly the working solution is provided.
I have created the column that will show days count between Today's date and Created Date. and this column is update automatically.
For this I have created one calculated column and added simple JavaScript on the SharePoint List view.
Step 1:
Create new calculated column in the list and give formula as follows

="<DIV ID='CreatedDate'>"&TEXT(Created,"MM/dd/yyyy")&"</DIV>"

Step 2:
Add Form Webpart(MOSS 2007) or HTML Form webpart(SharePoint 2010) on the view and  add below JavaScript in it.
<script type="text/javascript">   
// Script created by Amit Phule
// Taken reference from Christophe@PathToSharePoint.com post
  
        var theTDs = document.getElementsByTagName("TD");
        var i = 0;
        var TDContent = " ";
        while (i < theTDs.length) {
            try {
                TDContent = theTDs[i].innerText || theTDs[i].textContent;
                if ((TDContent.indexOf("<DIV ID='CreatedDate'") == 0) && (TDContent.indexOf("</DIV>") >= 0)) {
                    theTDs[i].innerHTML = getDateDiff(TDContent.replace('</DIV>', '').replace("<DIV ID='CreatedDate'>", ''));
                }
            }
            catch (err) { }
            i = i + 1;
        }
      
        // ExpGroupRenderData overwrites the default SharePoint function.  This part is needed for collapsed groupings      
        function ExpGroupRenderData(htmlToRender, groupName, isLoaded) {
            var tbody = document.getElementById("tbod" + groupName + "_");
            var wrapDiv = document.createElement("DIV");
            wrapDiv.innerHTML = "<TABLE><TBODY id=\"tbod" + groupName + "_\" isLoaded=\"" + isLoaded + "\">" + htmlToRender + "</TBODY></TABLE>";
            var theTBODYTDs = wrapDiv.getElementsByTagName("TD"); var j = 0; var TDContent = " ";
            while (j < theTBODYTDs.length) {
                try {
                    TDContent = theTBODYTDs[j].innerText || theTBODYTDs[j].textContent;
                    if ((TDContent.indexOf("<DIV ID='CreatedDate'") == 0) && (TDContent.indexOf("</DIV>") >= 0)) {
                        theTBODYTDs[j].innerHTML = TDContent;
                    }
                }
                catch (err) { }
                j = j + 1;
            }
            tbody.parentNode.replaceChild(wrapDiv.firstChild.firstChild, tbody);
        }
        function getDateDiff(Date2) {         
            var days = 0;
            var difference = 0;
            Christmas = new Date(Date2);
            today = new Date();
            difference = today - Christmas;
            days = Math.round(difference / (1000 * 60 * 60 * 24));
          if(days!=0)
            days = days - 1;
            return days;
        }
    </script>


Screenshot:

No comments:

Post a Comment