Get Week of Month in a Salesforce Formula Field
If you want to add a custom formula field to a standard or custom Salesforce object you have to get tricky as there is no built in function to return the week of the month based on a given starting day of the week. For this example we will assume we have an existing Date field called
If the week starts on Sunday and the 1st of the month is a Sunday we can just use
CEILING(Date__c/7) to figure it out. But what happens when the 1st is on a Monday? The 7th is now in the second week of the month and not the first.
Calculate Offset of the 1st
We can account for this by determining the index of the 1st of the month and then adding that to the
DAY(Date__c) value to accurately capture the week of the month. This means that if the first is a Monday, the index will be 1, and thus the
CEILING((7th + 1)/7) will give us week 2.
To get the day of the week offset we can start with a known Sunday the 1st –
1900-04-01 for example – and then get the number of days between it and the first of the month of the date we want to get the week of the month of. Once we have the difference in days we can take that value divided by 7 less the remainder to get the day of the week index.
CEILING( ( DAY( Date__c ) + MOD( DATE( YEAR( Date__c ), MONTH( Date__c ), 1 ) - DATE( 1900, 4, 1 ), 7 ) ) / 7 )