Determine if a String is a valid date before parsing

后端 未结 12 1652
半阙折子戏
半阙折子戏 2020-12-03 11:36

I have this situation where I am reading about 130K records containing dates stored as String fields. Some records contain blanks (nulls), some contain strings like this: \'

12条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 12:10

    Assuming the patterns you gave are the only likely choices, I would look at the String passed in to see which format to apply.

    public Date parseDate(final String date) {
      if (date == null) {
        return null;
      }
    
      SimpleDateFormat format = (date.charAt(2) == '/') ? new SimpleDateFormat("dd/MMM/yyyy")
                                                       : new SimpleDateFormat("dd-MMM-yy");
      try {
        return format.parse(date);
      } catch (ParseException e) {
        // Log a complaint and include date in the complaint
      }
      return null;
    }
    

    As others have mentioned, if you can guarantee that you will never access the DateFormats in a multi-threaded manner, you can make class-level or static instances.

提交回复
热议问题