problemeasyalgorithmsleetcode-2758leetcode 2758leetcode2758

Next Day

EasyUpdated: Aug 2, 2025
Practice on:

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.

Examples

Example 1:

Input: date = "2014-06-20"
Output: "2014-06-21"
Explanation: 
const date = new Date("2014-06-20");
date.nextDay(); // "2014-06-21"

Example 2:

Input: date = "2017-10-31"
Output: "2017-11-01"
Explanation: The day after 2017-10-31 is 2017-11-01.

Constraints:

  • new Date(date) is a valid date object

Solution

Method 1 -

Intuition

We need to add a method to the Date object that returns the next day in YYYY-MM-DD format. This can be done by extending Date.prototype.

Approach

Add a method nextDay to Date.prototype. In the method, create a new Date object, add one day, and format the result as YYYY-MM-DD.

Code

JavaScript
Date.prototype.nextDay = function() {
    const next = new Date(this.getTime());
    next.setDate(next.getDate() + 1);
    const yyyy = next.getFullYear();
    const mm = String(next.getMonth() + 1).padStart(2, '0');
    const dd = String(next.getDate()).padStart(2, '0');
    return `${yyyy}-${mm}-${dd}`;
}
Python (for reference)
from datetime import datetime, timedelta
def next_day(date_str):
    dt = datetime.strptime(date_str, "%Y-%m-%d")
    next_dt = dt + timedelta(days=1)
    return next_dt.strftime("%Y-%m-%d")
Java (for reference)
import java.time.LocalDate;
public String nextDay(String dateStr) {
    LocalDate date = LocalDate.parse(dateStr);
    return date.plusDays(1).toString();
}

Complexity

  • ⏰ Time complexity: O(1) for all methods.
  • 🧺 Space complexity: O(1).

Comments