How to check if String contains a date in a SimpleDateFormat and retrieve the date?

5.1k Views Asked by At

My code thus far:

String string = "Temp_2014_09_19_01_00_00.csv"  
SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd");

How can I check if the String contains a date? How can I retrieve this date? Any direction?

1

There are 1 best solutions below

0
On BEST ANSWER

Here is a simple example of using regex to do what you want(You might want to research regex on your own):

public static void main(String[] args) throws FileNotFoundException, ParseException {
    String string = "Temp_2014_09_19_01_00_00.csv";
    SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd");
    Pattern p = Pattern.compile("\\d\\d\\d\\d_\\d\\d_\\d\\d");
    Matcher m = p.matcher(string);
    Date tempDate = null;
    if(m.find())
    {
        tempDate = format.parse(m.group());
    }
    System.out.println("" + tempDate);
}

The regex looks for 4digits_2digits_2digits then it takes that match if it finds one and tries to convert it into a date. If it doesn't find a match then tempDate will be null. If you want to bring in the timestamp also you can do that too.