Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

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
share|improve this answer
    
I think this much more simpler. :) –  robertpeter07 Sep 3 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. –  robertpeter07 Sep 4 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 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. –  robertpeter07 Sep 4 at 6:22

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).

share|improve this answer
    
appreciated the effort to answer my question :) –  robertpeter07 Sep 4 at 3:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.