0

I have the program below which takes the user input from a string, parses into another format and then prints it again in another format.

How can I prevent the user from introducing a wrong format that would cause the date either to be displayed erroneously (ex. year 20222) or to cause a forward roll of the date (ex. introducing day 31 for a 30 day month causes to roll the month and set day to 01 of next month.).

ex. 2020-10-33 => 2020-11-3

I hope it makes sense!

public class Solution {

public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    String dater = reader.readLine();

    Date newDate = dateFormat.parse(dater);
    SimpleDateFormat dateFormat2 = new SimpleDateFormat("LLL dd, yyyy");

    System.out.println(dateFormat2.format(newDate).toUpperCase());
    reader.close();
}

}

Art
  • 39
  • 1
  • 9
  • You can prevent the user from entering invalid dates like the 33 february by setting the dateformat you use for parsing as non lenient: `dateFormat.setLenient(false)`. The year 20222 however is a perfectly valid year. If you want to not allow dates that while they are valid do not make sense logically you need to create your own custom validation. For example check if the parsed date is more than X-Years/Month in the future and throw your own custom errors. – OH GOD SPIDERS Nov 12 '20 at 15:56
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Nov 12 '20 at 15:57
  • First use `LocalDate newDate = LocalDate.parse(dater);` (that’s right, no formatter needed). This will throw a `DateTimeParseException` if the date is invalid. Next do a range check, for example `if (newDate.isBefore(LocalDate.now().minusYears(1)) || newDate.getYear() > Year.now().plusYears(100).getValue())`… – Ole V.V. Nov 12 '20 at 16:19
  • Great, thank you everyone for your answers, helped a lot! – Art Nov 13 '20 at 08:38

0 Answers0