Next Day - Problem

Write code that enhances all Date objects such that you can call the date.nextDay() method on any date object and it will return the next day in the format YYYY-MM-DD as a string.

Your task is to modify the Date prototype to add a nextDay() method that correctly handles:

  • Regular day increments
  • Month boundaries (e.g., January 31 → February 1)
  • Year boundaries (e.g., December 31 → January 1 of next year)
  • Leap years (February 28/29 transitions)

The method should return a string in ISO date format (YYYY-MM-DD) representing the day immediately following the given date.

Input & Output

Example 1 — Regular Day Increment
$ Input: dateString = "2023-06-15"
Output: "2023-06-16"
💡 Note: Simple case: June 15th becomes June 16th, no boundary crossing needed
Example 2 — Month Boundary
$ Input: dateString = "2023-01-31"
Output: "2023-02-01"
💡 Note: End of January rolls over to beginning of February
Example 3 — Year Boundary
$ Input: dateString = "2023-12-31"
Output: "2024-01-01"
💡 Note: New Year's Eve rolls over to New Year's Day of the next year

Constraints

  • Input date string is always in YYYY-MM-DD format
  • Year range: 1000 ≤ year ≤ 9999
  • Date represents a valid calendar date
  • Must handle leap years correctly

Visualization

Tap to expand
Next Day - Date Prototype Extension INPUT June 2023 Sun Mon Tue Wed Thu Fri Sat 12 13 14 16 17 15 Date Object new Date("2023-06-15") Thu Jun 15 2023 Input String: "2023-06-15" ALGORITHM STEPS 1 Extend Date Prototype Add nextDay() to Date.prototype 2 Create New Date Copy current date to avoid mutation 3 Add One Day setDate(getDate() + 1) Handles all boundaries 4 Format Output Return YYYY-MM-DD using toISOString() Date.prototype.nextDay = function() { let d = new Date(this); d.setDate(d.getDate()+1); } FINAL RESULT June 2023 16 --> 15 --> 16 Day incremented by 1 Output String: "2023-06-16" Handles Edge Cases: [OK] Month boundaries [OK] Year boundaries [OK] Leap years (Feb 29) Key Insight: JavaScript's Date.setDate() automatically handles month/year rollovers. When you add 1 to the last day of a month (e.g., Jan 31 + 1), it correctly becomes Feb 1. This built-in arithmetic also handles leap years, making the implementation simple and reliable. TutorialsPoint - Next Day | JavaScript Date Arithmetic
Asked in
Google 25 Amazon 20 Microsoft 18 Meta 15
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen