Category Archives: Sample codes

Salesforce: Adding specific working days to a Date

Many time while coding we come across the requirement in which we need to calculate the Enddate from a StartDate after specific number of business/working days. That means excluding the weekends (Saturday & Sunday) Following is the code snippet which does this. I know there can be optimize way for doing this. But I didn’t wanted to spend more time on this.

Below method takes date and number of working days to be added to the date.

global Datetime addBussinessDays(Datetime startDate, Integer iDays)
{
Datetime endDate = startDate.addDays(iDays);
Integer iOffDays = daysOff(startDate,endDate);
return endDate.addDays(iOffDays);
}

Method daysOff calculates the number of non-working days coming in the start date and end date. And after which we are again adding those number of days.

global Integer daysOff(Datetime sdate, Datetime edate)
{
Integer iCount = 0;
while (sdate < edate) {
if (sdate.format('E') == 'Sat' | sdate.format('E') == 'Sun'){
iCount = iCount + 1;
}
sdate = sdate.addDays(1);
}
return iCount;
}

Showing the Processing/Loading image

I came across a good code sample while surfing for showing the Loading/Processing  image on the VisualForce Page.

You can find it at: http://force.siddheshkabe.co.in/2009/10/displaying-please-wait-ajax-animation.html

Regex for AlphaNumeric password validation

Regular Expression for validating the string

(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,20})$

The above RegEx requires at least one digit, at least one alphabetic character, no special characters, and from 8-20 characters in length.

JavaScript: Number to Currency format conversion function

JavaScript for converting string to currency format.

function FormatToCurrency(num)
{
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents < 10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}