1

I need to write a logic to update a field with a date from next month. For example, today's date is 28/10/2020 11:00:00 AM, the field should be updated with 28/11/2020 11:00:00 AM. So just the value of month needs to be changed and also it needs to be handled when the year changes.

Kindly suggest what can be done in apex for this. The current logic that I have made is for adding 1 day.

DateTime dT1 = DateTime.Now().AddDays(1);
        String newDate = dT1.format('yyyy-MM-dd');
        String nextrun = newDate + ' ' + obj.Hour__c + ':' + obj.Minute__c+ ':'+'00'; 
        Datetime dt = DateTime.valueOf(nextrun);
        if(obj.Hour__c!='*'  && !(obj.Hour__c.contains(',')))
        {
            obj.Next_Run__c=  dt;
            update obj;
        }

Thanks, Surabhi Panwar

1 Answer 1

1

Following code snippet would work:

DateTime dt1 = DateTime.Now();
DateTime dt2 = DateTime.newInstance(dt1.year(), dt1.month()+1, dt1.day(), 
                            dt1.hour(), dt1.minute(), dt1.second());

Note that DateTime.newInstance automatically adjusts to correct day, month or year value. For example, if dt1 was 31-Oct-2020, then dt2 will be 01-Dec-2020 (since, there are only 30 days in Nov). Likewise, if dt1 was 12-Dec-2020, then dt2 will be 12-Jan-2021.

However, if this is not what you want (i.e., dt1 31-Oct-2020 should return dt2 as 30-Nov-2020), then you will have to write conditional apex code logic for few corner cases.

1
  • Thanks! I will give this a try and let you know if any challenges. Oct 29, 2020 at 14:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .