Monday, March 12, 2012

How to work with dates using XSL stylesheet

Calculating the difference between two dates and then do a decision based on the outcome can sometimes be tricky with XSL, because one only have the dates as numbers more or less. You don't have an Object of DateTime like you have with C# etc.

One requirement I often met is to format fields based on if a task is overdue or not, with some more logic like yellow lights to if its close to the due date. The easiest way to do this is often attaching a xsl:stylesheet to the list view. The tricky part is getting the days, months, years right. You have to compare the due date of the task up against the values for today, this is easy when they are in the same month when you can take the difference on days. The problems starts when they are in different months, and especially with months like February with leap years.

What I always do is that I first create all the variables for day, month and year for both the due date and today's date.

<xsl:variable name="MonthCurrent" select="number(substring-before(ddwrt:FormatDate(ddwrt:Today(),1033,1),'/'))"/>
<xsl:variable name="DayCurrent" select="number(substring-before(substring-after(ddwrt:FormatDate(ddwrt:Today(),1033,1),'/'),'/'))" />
<xsl:variable name="YearCurrent" select="number(substring-after(substring-after(ddwrt:FormatDate(ddwrt:Today(),1033,1),'/'),'/'))" />
<xsl:variable name="DueDay"  select="number(substring-before($thisNode/@DueDate,'.'))"/>
<xsl:variable name="DueMonth" select="number(substring-before(substring-after($thisNode/@DueDate,'.'),'.'))" />
<xsl:variable name="DueYear" select="number(substring-after(substring-after($thisNode/@DueDate,'.'),'.'))" />

Note that I have in this situation dates separated with ".", like 22.11.1983. But my system dates uses a "/", and returns the date as 11/22/1983.


Next part is to find how many days it is in the month:


   
     
        
     
     
        
     
     
        
     
     
       
     
   

Doing it this way it even checks for leap years.

Finally we can find number of days til due date. This is a simplified approach, because in most cases one don't need that many days before the due date. In this scenario its set to max 20 days.

  
    
      
    
    
      
    
    
     
    
    
     
    
    
     
    
                    

This is the variable you can use later in a stylesheet to check the number of days a task or similar are overdue or not. 

No comments:

Post a Comment