goe
goe

Reputation: 1243

Why do I get a date back when I pass a date string with a "HH" pattern to the SimpleDateFormat?

Here's my code:

try {
  DateFormat dateFormat = new SimpleDateFormat(pattern);
  dateFormat.setLenient(false);
  Date date = dateFormat.parse(value);
  if (date != null) {
    return true;
  }
} catch (ParseException e) {}

1.) When I pass value as "01/07/2015" and pattern as "HH:mm" I correctly get an exception.

2.) However when I pass value as "01/07/2015" and pattern as "HH" I get a "Thu Jan 01 01:00:00 EST 1970" Date object.

I would except scenario #2 to also throw an exception since the given string completely doesn't match the given pattern. Why do I get that strange date even when setLenient(false) is set?

Upvotes: 1

Views: 70

Answers (3)

goe
goe

Reputation: 1243

I found a solution to this problem. In order to resolve my issue I just wrapped my entire code in an if statement where I check if the length of the pattern is the same as the length of the value because they should be when I use this code for validation:

if(StringUtils.length(pattern) == StringUtils.length(value)) {
  try {
    DateFormat dateFormat = new SimpleDateFormat(pattern);
    dateFormat.setLenient(false);
    Date date = dateFormat.parse(value);
    if (date != null) {
      return true;
    }
  } catch (ParseException e) {}
}
return false;

Upvotes: 0

Magnilex
Magnilex

Reputation: 11958

The JavaDoc beautifully sums up why you do not get an exception:

Throws: ParseException - if the beginning of the specified string cannot be parsed.

01 can be parsed with HH, therefore no exception.

Upvotes: 1

Hiroaki Machida
Hiroaki Machida

Reputation: 1090

http://download.java.net/jdk6/archive/b104/docs/api/java/text/Format.html#parseObject(java.lang.String)

parseObject
public Object parseObject(String source)
                   throws ParseException
Parses text from the beginning of the given string to produce an object. The method may not use the entire text of the given string

I suppose #1 doesn't match the separator. You put / in it although the pattern is :.

And #2 stops matching right after HH because it parses text from the beginning of the given string and DOESN'T USE the entire text of the given string.

Upvotes: 1

Related Questions