1

I want to convert a String (with reserved characters) to Date in Java

I have a string with some reserved characters in it. I am getting it from some source. Also I get the format of it from the same source. I tried to convert that string to a date but I was unable to.

The date I get:

{ts '2021-03-24 12:52:38.933'}

The format I get:

'{ts' ''yyyy-MM-dd HH:mm:ss{.SSS}[Z]'''}'

I tried with the sample code snippet but since {} are reserved characters and also ts is an invalid character for parsing, I am unable to parse it. Please help with how I can solve this.

Obviously I can do some string manipulation and convert it to a format I want but I don't want to do that.

String dateInString = "{ts '2021-03-24 12:52:38.933'}";

SimpleDateFormat sdf = new SimpleDateFormat("{ts' ''yyyy-MM-dd HH:mm:ss{.SSS}[Z]'''}", Locale.ENGLISH);
try {
    Date date = sdf.parse(dateInString);
    System.out.println(date);
} catch (ParseException e) {
    e.printStackTrace();
}
Pawel Veselov
  • 3,996
  • 7
  • 44
  • 62
  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 19 '21 at 13:22

1 Answers1

3

You need to escape ' with another '.

Demo:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        String dateInString = "{ts '2021-03-24 12:52:38.933'}";
        SimpleDateFormat parser = new SimpleDateFormat("'{ts '''yyyy-MM-dd HH:mm:ss.SSS'''}'", Locale.ENGLISH);
        Date date = parser.parse(dateInString);
        System.out.println(date);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        System.out.println(formatter.format(date));
    }
}

Output:

Wed Mar 24 12:52:38 GMT 2021
2021-03-24T12:52:38.933

ONLINE DEMO

Note that the java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Solution using java.time, the modern Date-Time API:

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        String dateInString = "{ts '2021-03-24 12:52:38.933'}";
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("'{ts '''yyyy-MM-dd HH:mm:ss.SSS'''}'", Locale.ENGLISH);
        LocalDateTime ldt = LocalDateTime.parse(dateInString, parser);
        System.out.println(ldt);
    }
}

Output:

2021-03-24T12:52:38.933

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Thanks for the response. The format i get from the source is '{ts' ''yyyy-MM-dd HH:mm:ss{.SSS}[Z]'''}' and you have used '{ts '''yyyy-MM-dd HH:mm:ss.SSS'''}' so should i leave {.SSS}[Z] blindly ? – hari krishna Jun 19 '21 at 14:09
  • @harikrishna - The format should match the date-time string. The format that you are getting is not correct for the given date-time string. – Arvind Kumar Avinash Jun 19 '21 at 15:00