Calculate Worked Days\Days till now from list item’s Created Date in SharePoint

Sometimes you have to calculate days till now from a specific date for example to calculate Working days on a Task from the created date of the task. You can do this easily Using Today trick in calculated columns but that is just one time it is not daynamic and does not get update each day. To make the calculation dynamic I have used the EcmaScript\Javascrpt Client Object model.

Here is a short script which will calculate Days passed till now from the created date of an item.

For testing purposes you can copy and paste the script in a content editor webpart and change the List name. The script will output a table with Id of the Item along with the Days Passed or Days till now calculated from the Created date of the Item

 

<script type="text/javascript">

ExecuteOrDelayUntilScriptLoaded(DisplayDaysTillNow, "sp.js");

function DisplayDaysTillNow()
{

context = new SP.ClientContext.get_current();

web = context.get_web();

var list = web.get_lists().getByTitle('List Name');

var query = SP.CamlQuery.createAllItemsQuery();

this.listItems = list.getItems(query);

context.load(listItems,'Include(ID,Title,Created)');

context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod),

Function.createDelegate(this, this.onFailureMethod));
}

function onSuccessMethod(sender, args)
{

var result = new Array();

var ListEnumerator = this.listItems.getEnumerator();

var count = 0;

while(ListEnumerator.moveNext())
{

var currentItem = ListEnumerator.get_current();

var ID = currentItem.get_item('ID');

var Daystillnow = CalculateDays(currentItem.get_item('Created'));

result[count]= ID + "," + Daystillnow;

count++;
}

makeTable(listItems.get_count(),result);

}

function onFaiureMethod(sender, args)
{

}

function CalculateDays(CreatedDate)
{

var d = new Date();

var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds

var diffDays = Math.ceil((d.getTime() - CreatedDate.getTime())/(oneDay));

return diffDays;

}

function makeTable(rownum,result) {

row=new Array();
cell=new Array();

row_num=rownum; //edit this value to suit

cell_num=1; //edit this value to suit

tab=document.createElement('table');

tab.setAttribute('id','newtable');
tab.class="altrowstable";

tbo=document.createElement('tbody');

for(c=0;c<row_num;c++)
{

var mySplitResult = result[c].split(",");

row[c]=document.createElement('tr');

for(k=0;k<=cell_num;k++)
{
cell[k]=document.createElement('td');
cont=document.createTextNode(mySplitResult[k]);
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
tbo.appendChild(row[c]);
}
tab.appendChild(tbo);

document.getElementById('mytable').appendChild(tab);
}

</script>

<div id="mytable"></div>

 

Ads by google