blog.scoreman.net

Posts Tagged ‘Week Numbers’

Week numbers in calendar view – revisited for SharePoint 2010

Saturday, April 9th, 2011

A while ago I wrote a post on how to add week numbers to the monthly calendar view. The customer I built this for is now upgrading to SharePoint 2010 and since the calendar is now completely rebuild with ajax functionality I had to revisit and rewrite this code. This time I’m doing it with jQuery instead which in my opinion leads to a much cleaner solution. Thanks to Mike Smith’s post for showing how to intercept the asynchronous ajax events  of the calendar. The neet thing about this is that even if asynchronous events happen like if you page to a new month, the calendar still gets updated with new week numbers. For calculating week number I’m using the same javascript as in my post on how to add week numbers to the gantt view.

Week Numbers in Calendar

This is the code you need to put in a content editor web part on the same page as the calendar is displayed.

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.2.min.js" type="text/javascript"></script>
<script type="text/javascript">

Date.prototype.getWeek = function () {
   //lets calc weeknumber the cruel and hard way 😀
   //Find JulianDay
   var year = this.getFullYear();
   var month = this.getMonth();
   var day = this.getDate();

   month += 1; //use 1-12
   var a = Math.floor((14 - (month)) / 12);
   var y = year + 4800 - a;
   var m = (month) + (12 * a) - 3;
   var jd = day + Math.floor(((153 * m) + 2) / 5) +
                (365 * y) + Math.floor(y / 4) - Math.floor(y / 100) +
                Math.floor(y / 400) - 32045;      // (gregorian calendar)

   //now calc weeknumber according to JD
   var d4 = (jd + 31741 - (jd % 7)) % 146097 % 36524 % 1461;
   var L = Math.floor(d4 / 1460);
   var d1 = ((d4 - L) % 365) + L;
   NumberOfWeek = Math.floor(d1 / 7) + 1;
   return NumberOfWeek;
};

function updateCampaignCalendar() {

   // calendar rows
   jQuery('TH[evtid="week"]').each(function () {

      // add week numbers
      var firstDay = new Date(jQuery(this).attr('date'));
      if (firstDay.toString() != "NaN" && firstDay.toString() != "Invalid Date") {
         var week = firstDay.getWeek(firstDay.getDay());
         jQuery(this).children("DIV").attr("innerHTML", week);
      }
   });
}

_spBodyOnLoadFunctionNames.push('calendarEventLinkIntercept');

// hook into the existing SharePoint calendar load function
function calendarEventLinkIntercept() {
   var OldCalendarNotify4a = SP.UI.ApplicationPages.CalendarNotify.$4a;
   SP.UI.ApplicationPages.CalendarNotify.$4a = function () {
      OldCalendarNotify4a();
      updateCampaignCalendar();
   }
}
</script>