0

How do I validate a date(i mean that the date should not be invalid) using split method of string class? Further details: Each month should have their respective days and February should have 29 days only when it is a leap year and date should not exceed the present date.

12
  • Are you receiving dates as strings? and if so what's the format of the date written as? Commented Feb 28, 2014 at 13:30
  • and what have tried so far? Commented Feb 28, 2014 at 13:30
  • Uhm, you are aware that the JDK has classes to parse dates already? (SimpleDateFormat in this case) Commented Feb 28, 2014 at 13:30
  • You can use SimpleDateFormat Commented Feb 28, 2014 at 13:30
  • 1
    @user3364497 this depends on the initial format of your date to begin with Commented Feb 28, 2014 at 13:47

3 Answers 3

2

I can recomment to use validate(String value) method from Apache Commons DateValidator:

import org.apache.commons.validator.routines.DateValidator;
...

// Get the Date validator
DateValidator validator = DateValidator.getInstance();

// Validate/Convert the date
Date fooDate = validator.validate(fooString);
if (fooDate == null) {
    // error...not a valid date
    return;
}

validate() returns parsed Date if valid or null if invalid.

If you want only to get true/false, then there is another boolean method isValid(). For example:

DateValidator validator = DateValidator.getInstance();
if (validator.isValid(date)) {
    System.out.println(date + " is valid");
} else {
    System.out.println(date + " is invalid");
}
Sign up to request clarification or add additional context in comments.

4 Comments

and bro how i incorporate this into java?? i have no idea about apache.
@user3364497 see the javadoc for SimpleDateFormat; it is integrated into Java itself. What is more, a better library to handle time is Joda Time, if you want to use an external lib, use this one rather than Apache's
dude i know this, but i don't have the package.
Declare that import and download the commons-validator-1.4.0-bin.zip from mirror.ox.ac.uk/sites/rsync.apache.org//commons/validator/binaries/commons-validator-1.4.0-bin.zip. Then extract it and add commons-validator-1.4.0.jar to your build path.
1

In the JDK, you have SimpleDateFormat to handle this kind of stuff.

For instance, to validate an hour:

final DateFormat fmt = new SimpleDateFormat("HH:mm");

Then you can try and parse:

fmt.parse(input);

It will throw a ParseException if the date is invalid.

Of course, many other formats can be done.

As to external libraries, if you have to/want to use one, there is really only one to consider: Joda Time. It is so good a library that Java 8's new date API is 90+% inspired by it.

NOTE: JDK's as well as Joda Time's, parsers will derive missing components in a date from the current time; it means that if you try and parse a string containing Feb 29 in 2015, it will fail... But it will succeed in 2016 since it is a leap year!

2 Comments

nice one and best approach.
SimpleDateFormat will produce wrong results, try, for example, with String date = "32/02/2014";
0
convert string to date format, and this is easy for validating 

public class DateUtil {

    // List of all date formats that we want to parse.
    // Add your own format here.
//u can use anyone format
    private static List<SimpleDateFormat>; 
            dateFormats = new ArrayList<SimpleDateFormat>() {{
            add(new SimpleDateFormat("M/dd/yyyy"));
            add(new SimpleDateFormat("dd.M.yyyy"));
            add(new SimpleDateFormat("dd.M.yyyy hh:mm:ss a"));
            add(new SimpleDateFormat("dd.MMM.yyyy"));
            add(new SimpleDateFormat("dd-MMM-yyyy"));
        }
    };

    /**
     * Convert String with various formats into java.util.Date
     * 
     * @param input
     *            Date as a string
     * @return java.util.Date object if input string is parsed 
     *          successfully else returns null
     */
    public static Date convertToDate(String input) {
        Date date = null;
        if(null == input) {
            return null;
        }
        for (SimpleDateFormat format : dateFormats) {
            try {
                format.setLenient(false);
                date = format.parse(input);
            } catch (ParseException e) {
                //Shhh.. try other formats
            }
            if (date != null) {
                break;
            }
        }

        return date;
    }
}

4 Comments

Uh, in your try block you can just return format.parse(input); ;)
if it is 'Catch' means data is invalid and set return boolean value.its simple @fge
I am not talking about catch here but about your try block. If you do as I say, you don't even need to check for null after the catch, and you don't even need the date variable to begin with
yes i agree with you @fge,yours is simple,but,,my example provided different formats for user convenience.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.