Add Days to a Date
Problem
Read one line with a date (YYYY-MM-DD) and a whole number of days (it can be negative). Print the new date in the form YYYY-MM-DD.
Constraints
- Years 1900 to 2100 in input and result
Examples
Input
2024-02-28 2
Output
2024-03-01
Solutions
Date arithmetic must handle months with different lengths and leap years. The library does this for us.
/*
* Problem : Add days to a date.
* Input : A date and a number.
* Output : The new date.
* Approach: Use date arithmetic.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(String s) {
// Step 1: Split the line into the date text and the number of days.
String[] parts = s.trim().split(" ");
// Step 2: plusDays moves the date forward (or backward for a negative number). It knows the month lengths and leap years.
java.time.LocalDate date = java.time.LocalDate.parse(parts[0]).plusDays(Long.parseLong(parts[1]));
// Step 3: toString gives the ISO form YYYY-MM-DD.
return date.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- What happens when the number of days is negative?