0

I am currently trying to parse dates (and times) to convert them to milliseconds from epoch.

For this purpose I am using SimpleDateFormat for parsing with code like this:

public static long parseDate(String date) {
  // Parse
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
  Date parsedDate = format.parse(date);

  // Get milliseconds
  Calendar cal = new GregorianCalendar();
  cal.setTime(parsedDate);
  return cal.getTimeInMillis();
}

Playing around I discovered that SimpleDateFormat does allow parsing of 1970-00-00 which is parsed as 1969-11-30. Thinking about it, it completely makes sense. When the parser just "sums" everything so that 1969 is actually understood as '1969-11-30' and with 0 monts a "year-overflow" does not happen. Unfortunately, I does not change anything that this date is not valid (at least as I understand dates).

Is there a way to add validitation by not using third-party libs or java 8 (target is Android) or do have to stick with regex and validation by hand?

Thank you in advance!

tbolender
  • 1,172
  • 3
  • 14
  • 19

1 Answers1

1

Uh I am very sorry to have posted this question...

The answer is to disable the lenient flag with:

format.setLenient(false);

I do not remove this question so that if someone stumbles upon this does not need to spend hours figuring out how to change this... Hope it helps!

Which also leads me to the question why is this flag is enabled by default?

tbolender
  • 1,172
  • 3
  • 14
  • 19