- How to find a String contains fully on date formats, not an check with single date format, I want to check string with various formats?
- If a string matches with various formats means return boolean value.
- Is that possible to use a Date array?
This is the sample line of code:
Date[] dates = {"12/09/2014","2014/09/09"....};
Date d=new Date();
System.out.println("DATE :"+ new SimpleDateFormat("dd.M.yyyy").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("M/dd/yyyy").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("M/dd/yyyy hh:mm:ss a").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("dd.M.yyyy hh:mm:ss a").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("M/dd/yyyy").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("dd.MMM.yyyy").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("dd-MMM-yyyy").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("EEEE, MMMM d, yyyy HH:mm z").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("MMMM d, yyyy HH:mm z").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("EEE, MMM d, yyyy HH:mm z").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("MMM d, yyyy HH:mm z").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("EEE, MM/dd/yyyy HH:mm:ss z").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z").format(d));
System.out.println("DATE :"+ new SimpleDateFormat("EEE, M/d/yy hh:mm").format(d));
There are several ways to do this. For example, you can test several known date formats by setting them like this, then using a for-loop to check your date string.
// List of all date formats that you want to parse
private static List<simpledateformat>;
dateFormats = new ArrayList<simpledateformat>() {{
add(new SimpleDateFormat("M/dd/yyyy"));
add(new SimpleDateFormat("dd.M.yyyy"));
add(new SimpleDateFormat("M/dd/yyyy hh:mm:ss a"));
add(new SimpleDateFormat("dd.M.yyyy hh:mm:ss a"));
add(new SimpleDateFormat("dd.MMM.yyyy"));
add(new SimpleDateFormat("dd-MMM-yyyy"));
}
Here's a full implementation from another fellow: http://viralpatel.net/blogs/check-string-is-valid-date-java/
You can also use regular expressions. Here is some sample code to do what you' re asking: http://www.mkyong.com/regular-expressions/how-to-validate-date-with-regular-expression/