Why does SimpleDateFormat parse incorrect date?

后端 未结 2 1414
一生所求
一生所求 2020-11-29 09:20

I have date in string format and I want to parse that into util date.

var date =\"03/11/2013\"

I am parsing this as :

new S         


        
2条回答
  •  無奈伤痛
    2020-11-29 09:52

    You should use DateFormat.setLenient(false):

    SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    df.setLenient(false);
    df.parse("03/88/2013"); // Throws an exception
    

    I'm not sure that will catch everything you want - I seem to remember that even with setLenient(false) it's more lenient than you might expect - but it should catch invalid month numbers for example.

    I don't think it will catch trailing text, e.g. "03/01/2013 sjsjsj". You could potentially use the overload of parse which accepts a ParsePosition, then check the current parse index after parsing has completed:

    ParsePosition position = new ParsePosition(0);
    Date date = dateFormat.parse(text, position);
    if (position.getIndex() != text.length()) {
        // Throw an exception or whatever else you want to do
    }
    

    You should also look at the Joda Time API which may well allow for a stricter interpretation - and is a generally cleaner date/time API anyway.

提交回复
热议问题