How to escape single quote in java's SimpleDateFormat

According to the javadocs for SimpleDateFormat

Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote.

So a format string like:

"'{ts '''yyyy-MM-dd HH:mm:ss'''}'"

should match {ts '2012-08-13 02:30:01'}


Have you tried escaping the single quote by another single quote? Otherwise the better way might be to exctract the relevant part (between the quotes) using a regular expression, and only then applying the SimpleDateFormat.


tl;dr

LocalDateTime.parse( 
    "{ts '2012-08-13 02:30:01'}"
    .replace( "{ts '" , "" )       // Delete prefix.
    .replace( "'}" , "" )          // Delete suffix.
    .replace( " " , "T" )          // Yields `2012-08-13T02:30:01`. In standard ISO 8601 format.
)                                  // Returns a `LocalDateTime` object.

java.time

SimpleDateFormat is obsolete, supplanted years ago by the modern java.time classes defined in JSR 310.

java.time.DateTimeFormatter

Use DateTimeFormatter instead, to define formatting patterns for use in parsing/generating strings.

That class uses a pair of single quotes '' as the escape value for a single quote. Otherwise, a single quote is used to mark text to be ignored by the formatter.

Simple text manipulation to get ISO 8601 string

But no need for a custom formatting pattern in your case. Your inner text is nearly compliant with the ISO 8601 standard used by default in java.time. Just do some string manipulation of your input text.

String input = 
    "{ts '2012-08-13 02:30:01'}"
    .replace( "{ts '" , "" ) 
    .replace( "'}" , "" ) 
    .replace( " " , "T" )
;

Yields 2012-08-13T02:30:01.

Parse as LocalDateTime

Then parse as a LocalDateTime object.

LocalDateTime ldt = LocalDateTime.parse( input ) ;