How to check if String contains a only Date format

2019-08-10 04:09发布

问题:

  1. 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?
  2. If a string matches with various formats means return boolean value.
  3. Is that possible to use a Date array?

This is the sample line of code:

Date[] dates = {"12/09/2014","2014/09/09"....};

回答1:

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));


回答2:

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/