Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Date Parsing  RSS feed

 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. I'm trying to parse Strings (such as 12/15/07) into a java.util.Date object. When I know the format ahead of time, this is not a difficult task because I can specify what type of format to be looking for.

However, for this particular task, I do not know the date format ahead of time, so it could be "mm/dd/yy" or "mm/dd/yyyy." Is there some way to catch multiple date formats (preferably so I don't have to define all formats ahead of time, but I will if I need to - I was hoping there was some common set of formats).

Thank you.
Jeff
 
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmm...

do you know that the date will be in one of a given set of date formats? E.g. it will be either mm/dd/yy or mm/dd/yyyy? If so, you could try first one, then if that fails, try the next. If you also put these date formats in a properties file, you can add more formats later on:



If, on the other hand, the date format can be either mm/dd/yy or yy/mm/dd, without knowing which it will be difficult to parse 05/06/07 - is it 5. june 2007, or 7. june 2005?

Hope this helps.
 
Jeff Storey
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adne,

It is a good start. I am pretty sure that month will be before day, so it will be mm/dd/yyyy, but the other formats I was more concerned about were it could be things like:

12-15-07
12-15-2007
15 Dec 2007
December 15, 2007

and so forth.

I'm thinking that maybe I should look into using regular expressions for this (if the DateFormat class supports it) or maybe there is another way...

Thanks.
Jeff
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!