Java Date library accepts bad dates

236 views Asked by At

I'm trying to work with dates and experiencing a problem: java.util.Date library accepts bad dates from file for example: 2014/99/99 . Later it somehow converts it and from 2014/99/99 I get 2022/04/09. Is there an easy way to cope with this problem?

Here's the code:

Date ikalintasNuo = null;
static DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
private static Scanner scan;
ikalintasNuo = df.parse(scan.next());

Input from file : 2014/99/99 Output: 2022/04/09

1

There are 1 answers

0
Elliott Frisch On

I think you are looking for DateFormat.setLenient(boolean) like

static DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
static {
    df.setLenient(false);
}

As the linked Javadoc says,

Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.