user2147674
user2147674

Reputation: 2489

How to parse Date in a String with other text

I want to parse the following type of Date in a String, which can contain additional data before and after:

For example: foo-bar_2014-10-14_18.56.05_bar The following DateFormat doen't work:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss", Locale.ENGLISH);
Date result=df.parse(parent.getName());

Edit: Due to the the fact, that the text before and after could be anything like

I have created a regex which matches the date.

    String pattern="\\d\\d\\d\\d[-]\\d\\d[-]\\d\\d[_]\\d\\d.\\d\\d.\\d\\d";

Upvotes: 0

Views: 57

Answers (2)

mthmulders
mthmulders

Reputation: 9705

As the first part (before the date) is not known in advance, I think your only option is to remove the first "unknown" part.

Because the length of the date pattern is constant, you can always take the last 19 characters. That might be slightly more efficient than a regular expression, and might also be easier to understand.

Upvotes: 0

Daniel Jipa
Daniel Jipa

Reputation: 888

Use a regexp initially to locate the correct part of the string

    String name = "foo-bar_2014-10-14_18.56.05_bar";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss", Locale.ENGLISH);
    String pattern = "\\d{4}-\\d{2}-\\d{2}_\\d{2}\\.\\d{2}\\.\\d{2}";
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(name);
    if (m.find()) {
        System.out.println("Found value: " + m.group(0));
        Date result = df.parse(m.group(0));
        System.out.println("result: " + result);
    } else {
        System.out.println("NO MATCH");
    }       

Upvotes: 4

Related Questions