+ Start a Discussion
test269test269 

Urgent:Getting first/second/third/fourth sun/mon/tue.\/wed/thu/fri/sat of the current month

Hi,

 

      i want to get the first monday of the current month date.like this i want to get the nth day of the month in apex code only.

 

 

Any one can u please help me this.

 

Thanks in advance.

sfdcfoxsfdcfox
// Inputs:
// theDate: Any date in the month to check for.
// week: The 1st-5th week of month
// day: The 0th-6th day of week, as in Java

Date weekDayOfMonth(Date theDate, Integer week, Integer day) {
  Date tempDate =
    theDate.toStartOfMonth().toStartOfWeek().addDays(
      ((week-1)*7)+
      (day)+
      (theDate
        .toStartOfMonth()
        .toStartOfWeek()
        .daysBetween(theDate.toStartOfMonth()) < day ? 7 : 0)
    );
    if(tempDate.getMonth() != theDate.getMonth())
      tempDate = null;
    return tempDate;
}

This function should return the correct day in the correct week of the month, or null if that week/day value doesn't exist in the current month. I have not tested it, and it's written on the fly, so please feel free to adjust.