views:

480

answers:

3

I have to parse a custom date format in Java. It contains microseconds although Java doesn't provide support for microseconds. Because of that I filled the format with zeroes, but now I cannot parse date-strings with that format.

Is there a simple workaround or must I handle microseconds on my own (with String functions)?

@Test
public void testDateFormat() throws ParseException {
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS000");
    String theDate = format.format(new Date());
    // this will fail
    format.parse(theDate);
}
A: 

Add a '' around the zeros, like so: "yyyy-MM-dd-HH.mm.ss.SSS'000'"

Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.

laura
My testcase with single quotes still throws a ParseException.
Christian Strempfer
+2  A: 

Your problem is that the pattern used in SimpleDateFormat unfortunately have different meanings depending on whether it is used as a parser or as a formatter. As a formatter, your pattern does what is expected, the output will end with the millisecond value formatted as three digits followed by three 0 characters, e.g:

2010-01-25-14.17.47.307000

Used as a parser, the "SSS" pattern will however match an arbitrary number of digits and parse the above example as 307000 ms. After having parsed the ms field, the parser will still look for a "000" substring and fail with an exception, since you've reached the end of the input string, without fulfilling the requirements of the pattern.

Since there is no pattern for a µs value in SimpleDateFormat, you will have to write your own wrapper to strip the input string for the last three 0 characters, before feeding it to SimpleDateFormat.

jarnbjo
A: 

In addition to jarnbjo's answer, if you need the microseconds, you might be able to use java.sql.Timestamp:

Date dateToMillis = format.parse(theDate.substring(0, 23));
DateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Timestamp timestamp = Timestamp.valueOf(timestampFormat.format(dateToMillis) + theDate.substring(23,26));
Stephen Denne