Next Day Problem
#2758
Description
LeetCode Problem 2758.
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.
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
Approach: Add one UTC day
Copy the date (so the receiver is not modified), add one day, and format it as YYYY-MM-DD. toISOString() returns YYYY-MM-DDTHH:mm:ss.sssZ, so its first 10 characters are the wanted string.
Use the UTC variants (getUTCDate / setUTCDate): new Date("2014-06-20") is parsed as midnight UTC, and toISOString prints in UTC, so staying in UTC avoids an off-by-one day on machines in other time zones. setUTCDate also rolls over month and year ends (and leap days) correctly.
Complexity: Time O(1), space O(1).
/**
* @return {string}
*/
Date.prototype.nextDay = function () {
const date = new Date(this.getTime());
date.setUTCDate(date.getUTCDate() + 1);
return date.toISOString().slice(0, 10);
};