Working with dates
Write Apex · Beginner · 10 min · Runs in your Salesforce Developer org · Free
Scenario. A renewal workflow works out new dates from month-end and year-end dates.
Build Dates, cross a year end, add a month to Jan 31, and count the days between two dates.
What you will learn
Date.newInstance(year, month, day) makes a date. addDays and addMonths return a new Date, so save the result. year() returns the year as a number. daysBetween(other) counts the days to another date.
Date start = Date.newInstance(2024, 12, 31);
Date next = start.addDays(1);
Gotcha. Jan 31 plus one month is Feb 28, the last day of February. Also, 'Due: ' + someDate prints a midnight time, like 2025-01-01 00:00:00.
The task
Use Apex date math on two month-end dates and print what changes.
Examples:
- Dec 31, 2024 plus one day →
Next day: 2025-01-01 00:00:00andYear changed: true - Jan 31, 2025 plus one month →
Next month: 2025-02-28 00:00:00 - Jan 31 to Feb 28 →
Days apart: 28
Requirements:
- Create Dec 31, 2024 and Jan 31, 2025 with
Date.newInstance. - Add one day to Dec 31 and print
Next day:. Compare the twoyear()values and printYear changed:from that test. - Add one month to Jan 31 and print
Next month:with the new date. - Use
daysBetweento count the days from Jan 31 to the new date, and printDays apart:with that count.
Starter code
Date yearEnd = null;
Date nextDay = null;
Boolean yearChanged = false;
Date monthEnd = null;
Date nextMonth = null;
When it passes
Dec 31 plus one day lands in 2025, Jan 31 plus one month lands on Feb 28, and those two dates are 28 days apart.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.