1

I have a string with yyyyMMdd format and I want dd.MM.yyyy

I get this error with my code

java.lang.IllegalArgumentException: Cannot format given Object as a Date

String date = "20190226";
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");                  
date = sdf.format(date);

Any help?

  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 26 '19 at 18:16

2 Answers2

5

java.time

Java 8 and later versions you can use DateTimeFormatter.

Parsing text.

String str = "20190226";
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dateTime = LocalDate.parse(str, inputFormat);

Generating text.

DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("dd.MM.yyyy");
System.out.println(dateTime.format(outputFormat));

26.02.2019

Most of the java.time functionality is back-ported to Java 6 & Java 7 in the ThreeTen-Backport project. Further adapted for earlier Android (<26) in ThreeTenABP. See How to use ThreeTenABP….

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Prasann
  • 1,263
  • 2
  • 11
  • 18
3

You can parse a java.util.Date into a String like this:

    String dateStr = "20190226";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    Date date = sdf.parse(dateStr);
    sdf = new SimpleDateFormat("dd.MM.yyyy");
    dateStr = sdf.format(date);
tomgeraghty3
  • 1,234
  • 6
  • 10