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
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
-
-
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 useUtility.GetMonth(date.today().month()+1)
it will return January.– rpm07Sep 4, 2014 at 3:04 -
1Is there a reason why you use
Date.Today().month()+1
instead ofDate.Today().addMonths(1).month()
? As you said, the first statement will return 13 when it is December whileDate.Today().addMonths(1).month()
will return 1. It is safer to useDate.Today().addMonths(1).month()
.– svenfSep 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.– rpm07Sep 4, 2014 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).