0

I have a date stored in a string and I need to validate whether it represents a date or weekdate in ISODateFormat.

String is acceptable if it is in either format.

I can build 2 formatters and pass the string and check where they both throw exceptions and verify it.

String date;
final DateTimeFormatter dateFormatter = ISODateTimeFormat.date();
final DateTimeFormatter weekdateFormatter = ISODateTimeFormat.weekDate();
boolean isDate=true,isWeekDate=true;

try {
      dateFormatter.parseDateTime(date);
}
catch (IllegalArgumentException e) {
      isDate =false;
}

try {
    weekdateFormatter.parseDateTime(date);
}
catch (IllegalArgumentException e) {
    isWeekDate =false;
}

if(!isDate && !isWeekDate)
    throw UserDefinedException(); 

Is there any better way to do it?

demongolem
  • 9,474
  • 36
  • 90
  • 105
user1229441
  • 344
  • 4
  • 11

1 Answers1

0

additional method

   /**
    * @return null if string is invalid
    */
   public static DateTime checkDate(String dateAsString, DateTimeFormatter formatter)
   {
      DateTime retVal = null;
      try {
         retVal = formatter.parseDateTime(dateAsString);
      } catch (IllegalArgumentException ex){
      }
      return retVal;
   }  

usage

   String date = "someString";
   if (checkDate(date, ISODateTimeFormat.date()) == null 
      || checkDate(date, ISODateTimeFormat.weekDate()) == null) 
   {
      throw new UserDefinedException();
   }  

or utils method for multiple formats

   /**
    * @return null if string is invalid
    */
   public static DateTime checkDate(String dateAsString,
                                   DateTimeFormatter[] formatters)
   {
      DateTime retVal = null;
      for (final DateTimeFormatter formatter : formatters)
      {
         try
         {
            retVal = formatter.parseDateTime(dateAsString);
         }
         catch (IllegalArgumentException ex)
         {
         }
         if (retVal != null)
         {
            break;
         }
      }
      return retVal;
   }
Ilya
  • 29,135
  • 19
  • 110
  • 158