Add a specified number of months to a given date and return the resulting date. The number of months can be positive, negative, or zero. When the resulting day exceeds the number of days in the new month, the result rolls down to the last valid day of that month. Return null when the date input is null.

Examples:

Input: d = 2026-01-15, months = 3 Output: 2026-04-15 Explanation: Three months added produces April 15, 2026 Input: d = 2026-11-30, months = 3 Output: 2027-02-28 Explanation: Adding three months to November 30, 2026 lands in February 2027, clamped to the 28th Input: d = 2026-06-15, months = -6 Output: 2025-12-15 Explanation: Subtracting six months produces December 15, 2025 Input: d = 2026-06-15, months = 0 Output: 2026-06-15 Explanation: Zero months returns the original date Input: d = null, months = 5 Output: null Explanation: Null date returns null
Apex Code Editor

Welcome to Lightning Challenge!

Create an Account

Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.

Create account

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 All Time Leaderboard

Contest runs January 1, 1970 - December 31, 9999. Complete challenges to climb the leaderboard!

Points are calculated for challenges completed during the contest period.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In