Search code examples
javadatepreconditions

validate date in a particular format using preconditions


I have a date in string format YYYY/MM/DD HH:MM:SS which I need to validate using preconditions google guava class. I am using checkArgument method in lot of other places. How can I use checkArgument method to validate startDate to make sure it is in this format only YYYY/MM/DD HH:MM:SS and if they are not, then throw IllegalArgumentException with some message.

public Builder startDate(String startDate) {
    // validate startDate here using checkArgument if it is not valid then throw IllegalArgumentException.
    this.sDate = startDate;
    return this;
}

How can I use checkArgument method here?


Solution

  • Don't. Write

     try {
       new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(startDate);
     } catch (ParseException e) {
       throw new IllegalArgumentException(e);
     }
    

    ..which will also let you store the Date parsed and use it later. (Though, to be fair, java.util.Date is a terrible API best avoided -- but you implied you were using it in a previous question you appear to have deleted.)

    If you end up using Joda Time, http://joda-time.sourceforge.net/userguide.html#Input_and_Output explains how to adjust this answer for those needs.