0

I'm using Java 1.6. Is there a way to write a date format pattern that can parse both

2013-08-01

and

2013-08-01T00:00:00.000Z

? I have tried the following

yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

but it only matches the second, and dies with a ParseException on the first. My parse code is:

final DateFormat defaultDateFormatObj = new SimpleDateFormat(classDateFormat);
final java.util.Date startDate = defaultDateFormatObj.parse(myDateString);

Thanks, - Dave

Dave
  • 15,639
  • 133
  • 442
  • 830

2 Answers2

2

Doesn't seem to be possible to parse different formats in one DateFormatter

But, you can define one DateFormat for each one, and check for the presence of the "T" character, or the length of the date source, to decide which formatter to use.

I'd leave the try / catch to deal with really unparseable dates

Cristian Meneses
  • 4,013
  • 17
  • 32
1

In short, I don't believe so. I'd recommend using a try/catch with two different date formats (the second in the catch block).

The answer to this question should be helpful:

How to parse dates in multiple formats using SimpleDateFormat

Community
  • 1
  • 1
StormeHawke
  • 5,987
  • 5
  • 45
  • 73