3

I have the following code in Java.

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String expiryDateInString = "05/14/86";

final Instant expiryDate = dateFormat.parse((expiryDateInString)).toInstant();

I want this to cause a parse exception but i am getting a year parsed as 0086, which i believe is way in the past. How can i make the year to be a strictly 4 digit year and anything else will give an exception.

Saad
  • 915
  • 9
  • 19
  • *which i believe is way in the past.* - why do you believe that? – Scary Wombat May 16 '18 at 05:10
  • 1
    When you are using this SimpleDateFormat("MM/dd/yyyy"); then years in 4 digits, for 2 digits use SimpleDateFormat("MM/dd/yy"); – Adya May 16 '18 at 05:12
  • If its 2 digits or if the year is anything less than a 4 digit year. I want a parse exception. – Saad May 16 '18 at 05:13
  • Possible duplicate of [forcing 4 digits year in java's simpledateformat](https://stackoverflow.com/questions/3108561/forcing-4-digits-year-in-javas-simpledateformat) – Derrick May 16 '18 at 05:16
  • @Adya, op wants to prevent date with two digits year and throw expection. First understand the question and then comment. – Derrick May 16 '18 at 05:26
  • 2
    The time when you should use `SimpleDateFormatter` is way in the past. :-) That class is now long outdated and is also notoriously troublesome. And also I don’t know of a way to persuade it to behave as you want. In any case, today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. See [AxelH’s good answer](https://stackoverflow.com/a/50362941/5772882). – Ole V.V. May 16 '18 at 09:56

1 Answers1

5

Using java.time instead of the previous date API, you can use DateTimeFormatter that will throw an exception if it is not a correct year

DateTimeFormatter.ofPattern("MM/dd/uuuu").parse(("05/14/86")

Exception in thread "main" java.time.format.DateTimeParseException: Text '05/14/86' could not be parsed at index 6

DateTimeFormatter.ofPattern("MM/dd/uuuu").parse(("05/14/1986")

1986-05-14

In the opposite case, if you want to allow both 2 and 4 digit year, you can use the "optional" feature of the formatter using [ and ]. Providing both possible format for the year uuuu and uu in optional blocks, you will have :

DateTimeFormatter.ofPattern("MM/dd/[uuuu][uu]").parse(("05/14/86")

2086-05-14

DateTimeFormatter.ofPattern("MM/dd/[uuuu][uu]").parse(("05/14/1986")

1986-05-14

AxelH
  • 14,325
  • 2
  • 25
  • 55