Days Between Two Dates
Problem
Two dates are given on two lines in the form YYYY-MM-DD. Print the number of days from the first date to the second date. The result is negative if the second date is earlier.
Constraints
- Years 1900 to 2100
Examples
Input
2024-02-28 2024-03-01
Output
2
Solutions
Never count days by hand (leap years are hard). The date libraries know the calendar. We use UTC in JavaScript, so a daylight saving change can not add or remove an hour.
java.time was added in Java 8.
/*
* Problem : Count the days between two dates.
* Input : Two dates.
* Output : The number of days.
* Approach: Use the date library.
* 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 long solve(String a, String b) {
// Step 1: LocalDate is the date class of java.time (Java 8). parse reads the text YYYY-MM-DD.
java.time.LocalDate first = java.time.LocalDate.parse(a);
java.time.LocalDate second = java.time.LocalDate.parse(b);
// Step 2: ChronoUnit.DAYS.between counts the days from the first date to the second date.
return java.time.temporal.ChronoUnit.DAYS.between(first, second);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
String b = scanner.next();
System.out.println(solve(a, b));
}
}
Hints (2)
- Which class represents a date without a time in Java 8?
- Why use UTC in JavaScript?