3

If you use date.today().month()+4 how will you get its year. For instance, today's month is September and you add 4 in the month in the given statement above. We know that the year of the today's month that was added by 4 is 2015 because it will be January, how to get the exact year based on the month?

2 Answers 2

4

You can use the following code to get the exact year: Date.Today().addmonths(number).year();

Examples:

  • Date.Today().addmonths(3).year() will result in 2014
  • Date.Today().addmonths(4).year() will result in 2015
  • Date.Today().addmonths(16).year() will result in 2016
4
  • I think this much more simpler. :)
    – rpm07
    Sep 3, 2014 at 9:35
  • Date.Today().month()+1 would this be a wrong approach? what are the possible future error to this approach? Let's say the date today is December its value is 12, therefore when we add 1 it will become 13. However when we use Utility.GetMonth(date.today().month()+1) it will return January.
    – rpm07
    Sep 4, 2014 at 3:04
  • 1
    Is there a reason why you use Date.Today().month()+1 instead of Date.Today().addMonths(1).month()? As you said, the first statement will return 13 when it is December while Date.Today().addMonths(1).month() will return 1. It is safer to use Date.Today().addMonths(1).month().
    – svenf
    Sep 4, 2014 at 6:19
  • well as beginner in salesforce development, I still don't know some of the syntax, and what are the good practices. I'm in the process of developing while learning. That is why I asked.
    – rpm07
    Sep 4, 2014 at 6:22
1

Use a date variable in your code, then use the addMonths() method.

Date myDate = system.today();

myDate = myDate.addMonths(4);

system.debug(myDate);
system.debug(myDate.year());

The second debug statement correctly returns 2015 (as we are now into September).

1
  • appreciated the effort to answer my question :)
    – rpm07
    Sep 4, 2014 at 3:10

You must log in to answer this question.

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