How to check validity of Date String?

前端 未结 4 871
无人及你
无人及你 2020-12-04 01:16

In my project I need to check if a date string evaluates to a proper Date object. I\'ve decided to allow yyyy-MM-dd, and Date formats [(year, month, date) and (year, month,

4条回答
  •  北海茫月
    2020-12-04 01:58

    Just to show the final outcome, thanks to Csaba_H and Steve Kuo.

    private Date parseDate(String date){
    
        SimpleDateFormat[] possibleFormats = new SimpleDateFormat[] {
            new SimpleDateFormat("yyyy-MM-dd"),
            new SimpleDateFormat("yyyy,MM,dd"),
            new SimpleDateFormat("yyyy,MM,dd,HH,mm") };
    
        Date retVal = null;
        for (SimpleDateFormat f: possibleFormats) {
            f.setLenient(false);
            try {
                retVal = f.parse(date);
            } catch (ParseException e) {}
        }
        return retVal;
    }
    

提交回复
热议问题