How to escape single quote in java's SimpleDateFormat

Viewed 5796

I have a date input date like this: {ts '2012-08-13 02:30:01'}

I believe I can escape the invalid part with single quotes, but I have a single quote within the invalid part. How do I escape that? I tried a couple of patterns but it is not working.

Thanks,

4 Answers

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 ) ;

This is what worked for me

SimpleDateFormat("dd MMM''yy", Locale.ENGLISH)

01 Jan'20
Related