Search code examples
javadatedatetimesimpledateformatdatetime-parsing

Convert or format string to date


I am struggling with this .. I have an input string - like this: 2021-10-13 11:33:16.000-04

Using Java.

I need to get a Date object from it. which formatting pattern can I use ?

I try with these

SimpleDateFormat inFormatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSS'-'ZZ");

and

SimpleDateFormat inFormatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSSZZ");

and I keep getting

java.text.ParseException: Unparseable date: "2021-10-13 11:33:16.000-04"
  at java.base/java.text.DateFormat.parse(DateFormat.java:396)
  at com.dima.tests.DatesConversions.main(DatesConversions.java:24)

Please, help !!


Solution

  • Since you are using ISO 8601 time zone timezone, you have the use the below pattern.

    SimpleDateFormat inFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSX");
    

    And then, to get the date:

    Date date = inFormatter.parse("2021-10-13 11:33:16.000-04");
    

    Always check the documentation.