function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
degmodegmo 

Get same day of next year in Apex

Hi,
I need to add 1 year to date but the new date needs to fall in same day of week.  For example, if my starting date is Saturday 7/24/2021, I want the new date to be Saturday 7/23/2022.  If I do .addYears(1), I am getting 7/24/2022 which is a Sunday.  Any suggestions?

 
PriyaPriya (Salesforce Developers) 

Hi Degmo,

Did you try using the function "Year". Please try something like below :- 

Year(Date field) + 1

please let me know if it meet your need.

regards,

Priya Ranjan

CharuDuttCharuDutt
Hii Degmo
Try Below Code
Apex
date myDate = Sytem.Today();
System.Debug('Before===> '+ myDate);
date newDate = myDate.addYears(1);
System.Debug('After==>' +newDate);


Formula OR Validation

Year(Date) + 1
Please Mark It As Best Answer If It Helps
Thank You!
Suraj Tripathi 47Suraj Tripathi 47

Hi,

Please find the solution.

I think the below code is working fine if any changes are required, please do some need full changes.

Public static void data1(){
        DateTime myDate=Date.today();
        String dayOfWeek=myDate.format('EEEE');
         System.debug('Day : ' + dayOfWeek);
                DateTime newDate=myDate.addYears(1);
 
        DateTime answer;
        
        for(Integer i=0;i<6;i++){
             DateTime newDates=myDate.addDays(i);
           
            String newDayOfWeek=newDates.format('EEEE');
             system.debug('Inside newDayOfWeek'+newDayOfWeek);
            if(dayOfWeek==newDayOfWeek){
                answer=newDates;
                system.debug('answer'+answer);
                
            }
            
        }
        
      
    }


Please mark it as the Best Answer so that other people would take references from it.

Thank You

degmodegmo
@priya and @charudutt, your suggestions doesn't work because all it does is just add one year to the current date.

@suraj,
your code is on the right path but it's flawed some.  If I pass in a date 7/25/2021, I get 7/31/2022.  But what I need is 7/24/2022.