2

For a certain API I am getting dates in a /Date(1323312018479-0700)/ format. For some reason the regex that I am using does not result in any matches.

Any ideas?

BTW: I am not taking into account the timezone right now.

public static Date parseApiDate(String rawDate) {
    Pattern p = Pattern.compile("([0-9]+)-([0-9]+)", Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(rawDate);

    Log.d("DATE CONVERSION: Raw", rawDate);
    if (m.matches()) {
        String utc = m.group(1);
        int milliSeconds = Integer.parseInt(utc);
        Date date = new Date(milliSeconds);

        Log.d("DATE CONVERSION: milliseconds", utc);
        Log.d("DATE CONVERSION: Converted", date.toGMTString());

        return date;
    } else {    
        return new Date(0);
    }
}
1
  • If it's of the same format always, you can use string parsing, which would be better. Commented Dec 7, 2011 at 22:48

2 Answers 2

3

You need m.find() instead of m.matches(). Then you'd need Long.parseLong()

Generally, you should parse dates with DateFormat (SimpleDateFormat), but in this case it can't cope. The pattern SZ fails, perhaps because it is not sure where the timezone starts (although it should be able to do that)

Sign up to request clarification or add additional context in comments.

1 Comment

I got hung up on the regex and missed the the fact that I was trying to convert a long to an int, which was the sole cause.
0

Try it with

Pattern p = Pattern.compile(".*?([0-9]+)-([0-9]+).*?", Pattern.CASE_INSENSITIVE);

2 Comments

@chris - You need to combine this answer with what Bozho mentioned about using Long.
The regex actually works fine without the addition lazy expression addition. The exception that was being thrown wasn't printing the stacktrace which is why I kept thinking that it was the problem.

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.