SimpleDateFormat parse(string str) doesn't throw an exception when str = 2011/12/12aaaaaaaaa?
Asked Answered
F

7

12

Here is an example:

public MyDate() throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
    sdf.setLenient(false);
    String t1 = "2011/12/12aaa";
    System.out.println(sdf.parse(t1));
}

2011/12/12aaa is not a valid date string. However the function prints "Mon Dec 12 00:00:00 PST 2011" and ParseException isn't thrown.

Can anyone tell me how to let SimpleDateFormat treat "2011/12/12aaa" as an invalid date string and throw an exception?

Frau answered 8/12, 2011 at 8:44 Comment(0)
R
14

The JavaDoc on parse(...) states the following:

parsing does not necessarily use all characters up to the end of the string

It seems like you can't make SimpleDateFormat throw an exception, but you can do the following:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
sdf.setLenient(false);
ParsePosition p = new ParsePosition( 0 );
String t1 = "2011/12/12aaa";    
System.out.println(sdf.parse(t1,p));

if(p.getIndex() < t1.length()) {
  throw new ParseException( t1, p.getIndex() );
}

Basically, you check whether the parse consumed the entire string and if not you have invalid input.

Robertson answered 8/12, 2011 at 8:48 Comment(0)
A
5

To chack whether a date is valid The following method returns if the date is in valid otherwise it will return false.

public boolean isValidDate(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }
        catch (ParseException e) {
            return false;
        }
        if (!sdf.format(testDate).equals(date)) {
            return false;
        }
        return true;

    }

Have a look on the following class which can check whether the date is valid or not

** Sample Example**

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateValidCheck {


    public static void main(String[] args) {

        if(new DateValidCheck().isValidDate("2011/12/12aaa")){
            System.out.println("...date is valid");
        }else{
            System.out.println("...date is invalid...");
        }

    }


    public boolean isValidDate(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }
        catch (ParseException e) {
            return false;
        }
        if (!sdf.format(testDate).equals(date)) {
            return false;
        }
        return true;

    }

}
Andi answered 8/12, 2011 at 9:46 Comment(0)
S
4

Java 8 LocalDate may be used:

public static boolean isDate(String date) {
    try {
        LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return true;
    } catch (DateTimeParseException e) {
        return false;
    }
}

If input argument is "2011/12/12aaaaaaaaa", output is false;

If input argument is "2011/12/12", output is true

Superabundant answered 16/5, 2017 at 8:26 Comment(0)
M
2

After it successfully parsed the entire pattern string SimpleDateFormat stops evaluating the data it was given to parse.

Marismarisa answered 8/12, 2011 at 9:3 Comment(0)
E
0

You can use the ParsePosition class or the sdf.setLenient(false) function

Docs: http://docs.oracle.com/javase/7/docs/api/java/text/ParsePosition.html http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient(boolean)

Ezzell answered 8/12, 2011 at 8:53 Comment(3)
I think parse method only care about the start pos, not the end pos. isLenient doesn't workFrau
When linking JavaDocs, please try to link the current version (which is 7, not 1.4.2).Robertson
@TerminalUser mm I tried it myself with an example but setLeniet() doesn't seems to work and ParsePosition only works when there is actually a exception thrown. You can check if both Strings have the same length after parseing without an Exception and then throw an exception manual. Not fully what you request but...Ezzell
E
0

Take a look on the method documentation which says: ParseException if the beginning of the specified string cannot be parsed.

Method source code with javadoc:

/**
 * Parses text from the beginning of the given string to produce a date.
 * The method may not use the entire text of the given string.
 * <p>
 * See the {@link #parse(String, ParsePosition)} method for more information
 * on date parsing.
 *
 * @param source A <code>String</code> whose beginning should be parsed.
 * @return A <code>Date</code> parsed from the string.
 * @exception ParseException if the beginning of the specified string
 *            cannot be parsed.
 */
public Date parse(String source) throws ParseException
{
    ParsePosition pos = new ParsePosition(0);
    Date result = parse(source, pos);
    if (pos.index == 0)
        throw new ParseException("Unparseable date: \"" + source + "\"" ,
            pos.errorIndex);
    return result;
}
Eddo answered 8/12, 2011 at 8:58 Comment(0)
D
-1

Simply setting sdf.setLenient(false) will do the trick..

Dermott answered 12/4, 2019 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.