Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

java - How to check validity of Date String?

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, date, hrs, min)]. How can I check if they're valid ? My code returns null for "1980-01-01" and some strange dates (like 3837.05.01) whon giving a string separated by commas :

private Date parseDate(String date){
    Date data = null;

    // yyy-mm-dd
    try {
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
        df.setLenient(false);
        df.parse(date);
        return data;
    }
    catch (Exception e) {
        try{
            int[] datArr = parseStringForDate(date);
            int len = datArr.length;
            // year, month, day
            if(len == 3){
                return new Date(datArr[0], datArr[1], datArr[2]);
            }
            // year, montd, day, hours, mins
            else if(len ==5){
                return new Date(datArr[0], datArr[1], datArr[2], datArr[3], datArr[4]);
            }
            // year, month, day, hours, mins, secs
            else if(len == 6){
                return new Date(datArr[0], datArr[1], datArr[2], datArr[3], datArr[4], datArr[5]);
            }
            else {
                return data;
            }
        }
        catch (Exception f){
            return data;
        }
    }
}

private int[] parseStringForDate(String s){
    String[] sArr = s.split(",");
    int[] dateArr = new int[sArr.length];

    for(int i=0; i< dateArr.length; i++){
        dateArr[i] = Integer.parseInt(sArr[i]);
    }

    return dateArr;
}

I remember that I had to subtract 1900 from year date, but I also see that month is different etc, and I'd like to avoid checking every element of my array of ints from date string. Is it possible to parse them automatically in Calendar or date object ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can construct SimpleDateFormat objects for your different String formats like this (returning null if the parameter cannot be parsed as a valid date):

// Initializing possibleFormats somewhere only once
SimpleDateFormat[] possibleFormats = new SimpleDateFormat[] {
  new SimpleDateFormat("yyyy-MM-dd"),
  new SimpleDateFormat("yyyy,MM,dd"),
  new SimpleDateFormat("yyyy,MM,dd,HH,mm") };
for (SimpleDateFormat format: possibleFormats)
{
  format.setLenient(false);
}
// initializing ends

public Date parseDate(String date) {
  Date retVal = null;
  int index = 0;
  while (retVal == null && index < possibleFormats.length) {
    try {
      retVal = possibleFormats[index++].parse(date);
    } catch (ParseException ex) { /* Do nothing */ }
  }
  return retVal;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...