user1503699
user1503699

Reputation: 55

How to parse string input that may have different date format?

E.g. i might have input string like below:

2012-07-23T03:30:00.000Z

or

2012-06-25T13:00:00.000+08:00

For these two case, i have different date formats to parse like e.g. if is 2012-07-23T03:30:00.000Z then i need to use yyyy-MM-dd'T'KK:mm:ss'.000Z

then if is 2012-06-25T13:00:00.000+08:00 i need to use yyyy-MM-dd'T'KK:mm:ss'.000+08:00

is it ok to do a date parsing to find out the format?

But if i parse then in my logs files i may see many exception being thrown out.

Or is there an more elegant way of handling this issue?

Thanks

Upvotes: 0

Views: 868

Answers (2)

Keith Randall
Keith Randall

Reputation: 23265

You can parse the different time formats using a try/catch block for each possible format. Only if all the parsings fail do you pass on the exception.

Upvotes: 1

jjathman
jjathman

Reputation: 12604

I'd recommend using DateUtils from the commons-lang project. You can pass it a series of formats to try and parse your date. Very clean if you ask me. http://commons.apache.org/lang/api-3.1/org/apache/commons/lang3/time/DateUtils.html#parseDate(java.lang.String, java.lang.String...)

For example:

Date d = DateUtils.parse("2012-01-01", "yyyyMMdd", "MM/dd/yyyy", "yyyy-MM-dd");

Will successfully parse because the final pattern will work.

Upvotes: 1

Related Questions