LocalDate from java.time
Read the start date from the user
I suggest that you ask the user to input the date in a format defined by the default locale. Users will be happy to use a format that they recognize as common in their culture. To help the user type the correct format, first output both the format and an example date in that format. For example:
Locale userLocale = Locale.getDefault(Locale.Category.FORMAT);
String dateFormat = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT, null, IsoChronology.INSTANCE, userLocale);
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(userLocale);
LocalDate exampleDate = LocalDate.of(2019, Month.OCTOBER, 23);
System.out.println("Enter start date in format " + dateFormat
+ ", for example " + exampleDate.format(dateFormatter));
In US locale this will print:
Enter start date in format M/d/yy, for example 10/23/19
In German locale, for example, the output is different:
Enter start date in format dd.MM.yy, for example 23.10.19
Now read the date as a string from the user and parse it using the same formatter.
LocalDate arrivalDate = null;
do {
String inputDateString = yourInputScanner.nextLine();
try {
arrivalDate = LocalDate.parse(inputDateString, dateFormatter);
} catch (DateTimeParseException dtpe) {
System.out.println(inputDateString + " is not in the correct format, please try again");
}
} while (arrivalDate == null);
If this was for a graphical user interface, one would typically use a date picker rather than textual input. There are some available, use your search engine.
Read the length of the date range from the user
Have the user input the number of weeks they want to stay, either 1 or 2. Inform them of the end date in each case.
LocalDate departureDate7 = arrivalDate.plusWeeks(1);
LocalDate departureDate14 = arrivalDate.plusWeeks(2);
System.out.println("Enter the number of weeks of the stay,"
+ " 1 for departure date " + departureDate7.format(dateFormatter)
+ ", 2 for departure date " + departureDate14.format(dateFormatter));
Example output (US locale, input 12/20/19
):
Enter the number of weeks of the stay, 1 for departure date 12/27/19,
2 for departure date 1/3/20
Based on the user input select the corresponding departure date.
Avoid Date and SimpleDateFormat
The classes Date
and SimpleDateFormat
used in the other answers are poorly designed, the latter notoriously troublesome. They are also long outdated. Don’t use them. Instead I am using java.time, the modern Java date and time API. A LocalDate
is a date without time of day, which seems to be what you need here.
Links